creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts/math/SafeMath.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n    /**\n     * @dev Returns the addition of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        uint256 c = a + b;\n        if (c < a) return (false, 0);\n        return (true, c);\n    }\n\n    /**\n     * @dev Returns the substraction of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        if (b > a) return (false, 0);\n        return (true, a - b);\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\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     * @dev Returns the division of two unsigned integers, with a division by zero flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        if (b == 0) return (false, 0);\n        return (true, a / b);\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        if (b == 0) return (false, 0);\n        return (true, a % b);\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `+` operator.\n     *\n     * Requirements:\n     *\n     * - Addition cannot overflow.\n     */\n    function add(uint256 a, uint256 b) internal pure returns (uint256) {\n        uint256 c = a + b;\n        require(c >= a, \"SafeMath: addition overflow\");\n        return c;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting on\n     * overflow (when the result is negative).\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     *\n     * - Subtraction cannot overflow.\n     */\n    function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n        require(b <= a, \"SafeMath: subtraction overflow\");\n        return a - b;\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `*` operator.\n     *\n     * Requirements:\n     *\n     * - Multiplication cannot overflow.\n     */\n    function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (a == 0) return 0;\n        uint256 c = a * b;\n        require(c / a == b, \"SafeMath: multiplication overflow\");\n        return c;\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers, reverting on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity's `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function div(uint256 a, uint256 b) internal pure returns (uint256) {\n        require(b > 0, \"SafeMath: division by zero\");\n        return a / b;\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * reverting when dividing by zero.\n     *\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n        require(b > 0, \"SafeMath: modulo by zero\");\n        return a % b;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n     * overflow (when the result is negative).\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {trySub}.\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     *\n     * - Subtraction cannot overflow.\n     */\n    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        require(b <= a, errorMessage);\n        return a - b;\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n     * division by zero. The result is rounded towards zero.\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {tryDiv}.\n     *\n     * Counterpart to Solidity's `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        require(b > 0, errorMessage);\n        return a / b;\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * reverting with custom message when dividing by zero.\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {tryMod}.\n     *\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        require(b > 0, errorMessage);\n        return a % b;\n    }\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.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(address sender, address recipient, uint256 amount) 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"
      },
      "@openzeppelin/contracts/utils/Counters.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../math/SafeMath.sol\";\n\n/**\n * @title Counters\n * @author Matt Condon (@shrugs)\n * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number\n * of elements in a mapping, issuing ERC721 ids, or counting request ids.\n *\n * Include with `using Counters for Counters.Counter;`\n * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}\n * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never\n * directly accessed.\n */\nlibrary Counters {\n    using SafeMath for uint256;\n\n    struct Counter {\n        // This variable should never be directly accessed by users of the library: interactions must be restricted to\n        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add\n        // this feature: see https://github.com/ethereum/solidity/issues/4637\n        uint256 _value; // default: 0\n    }\n\n    function current(Counter storage counter) internal view returns (uint256) {\n        return counter._value;\n    }\n\n    function increment(Counter storage counter) internal {\n        // The {SafeMath} overflow check can be skipped here, see the comment at the top\n        counter._value += 1;\n    }\n\n    function decrement(Counter storage counter) internal {\n        counter._value = counter._value.sub(1);\n    }\n}\n"
      },
      "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport './pool/IUniswapV3PoolImmutables.sol';\nimport './pool/IUniswapV3PoolState.sol';\nimport './pool/IUniswapV3PoolDerivedState.sol';\nimport './pool/IUniswapV3PoolActions.sol';\nimport './pool/IUniswapV3PoolOwnerActions.sol';\nimport './pool/IUniswapV3PoolEvents.sol';\n\n/// @title The interface for a Uniswap V3 Pool\n/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform\n/// to the ERC20 specification\n/// @dev The pool interface is broken up into many smaller pieces\ninterface IUniswapV3Pool is\n    IUniswapV3PoolImmutables,\n    IUniswapV3PoolState,\n    IUniswapV3PoolDerivedState,\n    IUniswapV3PoolActions,\n    IUniswapV3PoolOwnerActions,\n    IUniswapV3PoolEvents\n{\n\n}\n"
      },
      "@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolActions.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissionless pool actions\n/// @notice Contains pool methods that can be called by anyone\ninterface IUniswapV3PoolActions {\n    /// @notice Sets the initial price for the pool\n    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value\n    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96\n    function initialize(uint160 sqrtPriceX96) external;\n\n    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position\n    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback\n    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends\n    /// on tickLower, tickUpper, the amount of liquidity, and the current price.\n    /// @param recipient The address for which the liquidity will be created\n    /// @param tickLower The lower tick of the position in which to add liquidity\n    /// @param tickUpper The upper tick of the position in which to add liquidity\n    /// @param amount The amount of liquidity to mint\n    /// @param data Any data that should be passed through to the callback\n    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback\n    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback\n    function mint(\n        address recipient,\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount,\n        bytes calldata data\n    ) external returns (uint256 amount0, uint256 amount1);\n\n    /// @notice Collects tokens owed to a position\n    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.\n    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or\n    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the\n    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.\n    /// @param recipient The address which should receive the fees collected\n    /// @param tickLower The lower tick of the position for which to collect fees\n    /// @param tickUpper The upper tick of the position for which to collect fees\n    /// @param amount0Requested How much token0 should be withdrawn from the fees owed\n    /// @param amount1Requested How much token1 should be withdrawn from the fees owed\n    /// @return amount0 The amount of fees collected in token0\n    /// @return amount1 The amount of fees collected in token1\n    function collect(\n        address recipient,\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount0Requested,\n        uint128 amount1Requested\n    ) external returns (uint128 amount0, uint128 amount1);\n\n    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position\n    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0\n    /// @dev Fees must be collected separately via a call to #collect\n    /// @param tickLower The lower tick of the position for which to burn liquidity\n    /// @param tickUpper The upper tick of the position for which to burn liquidity\n    /// @param amount How much liquidity to burn\n    /// @return amount0 The amount of token0 sent to the recipient\n    /// @return amount1 The amount of token1 sent to the recipient\n    function burn(\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount\n    ) external returns (uint256 amount0, uint256 amount1);\n\n    /// @notice Swap token0 for token1, or token1 for token0\n    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback\n    /// @param recipient The address to receive the output of the swap\n    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0\n    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)\n    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this\n    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap\n    /// @param data Any data to be passed through to the callback\n    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive\n    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive\n    function swap(\n        address recipient,\n        bool zeroForOne,\n        int256 amountSpecified,\n        uint160 sqrtPriceLimitX96,\n        bytes calldata data\n    ) external returns (int256 amount0, int256 amount1);\n\n    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback\n    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback\n    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling\n    /// with 0 amount{0,1} and sending the donation amount(s) from the callback\n    /// @param recipient The address which will receive the token0 and token1 amounts\n    /// @param amount0 The amount of token0 to send\n    /// @param amount1 The amount of token1 to send\n    /// @param data Any data to be passed through to the callback\n    function flash(\n        address recipient,\n        uint256 amount0,\n        uint256 amount1,\n        bytes calldata data\n    ) external;\n\n    /// @notice Increase the maximum number of price and liquidity observations that this pool will store\n    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to\n    /// the input observationCardinalityNext.\n    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store\n    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;\n}\n"
      },
      "@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that is not stored\n/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the\n/// blockchain. The functions here may have variable gas costs.\ninterface IUniswapV3PoolDerivedState {\n    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp\n    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing\n    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,\n    /// you must call it with secondsAgos = [3600, 0].\n    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in\n    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.\n    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned\n    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp\n    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block\n    /// timestamp\n    function observe(uint32[] calldata secondsAgos)\n        external\n        view\n        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);\n\n    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range\n    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.\n    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first\n    /// snapshot is taken and the second snapshot is taken.\n    /// @param tickLower The lower tick of the range\n    /// @param tickUpper The upper tick of the range\n    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range\n    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range\n    /// @return secondsInside The snapshot of seconds per liquidity for the range\n    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)\n        external\n        view\n        returns (\n            int56 tickCumulativeInside,\n            uint160 secondsPerLiquidityInsideX128,\n            uint32 secondsInside\n        );\n}\n"
      },
      "@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolEvents.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Events emitted by a pool\n/// @notice Contains all events emitted by the pool\ninterface IUniswapV3PoolEvents {\n    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool\n    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize\n    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96\n    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool\n    event Initialize(uint160 sqrtPriceX96, int24 tick);\n\n    /// @notice Emitted when liquidity is minted for a given position\n    /// @param sender The address that minted the liquidity\n    /// @param owner The owner of the position and recipient of any minted liquidity\n    /// @param tickLower The lower tick of the position\n    /// @param tickUpper The upper tick of the position\n    /// @param amount The amount of liquidity minted to the position range\n    /// @param amount0 How much token0 was required for the minted liquidity\n    /// @param amount1 How much token1 was required for the minted liquidity\n    event Mint(\n        address sender,\n        address indexed owner,\n        int24 indexed tickLower,\n        int24 indexed tickUpper,\n        uint128 amount,\n        uint256 amount0,\n        uint256 amount1\n    );\n\n    /// @notice Emitted when fees are collected by the owner of a position\n    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees\n    /// @param owner The owner of the position for which fees are collected\n    /// @param tickLower The lower tick of the position\n    /// @param tickUpper The upper tick of the position\n    /// @param amount0 The amount of token0 fees collected\n    /// @param amount1 The amount of token1 fees collected\n    event Collect(\n        address indexed owner,\n        address recipient,\n        int24 indexed tickLower,\n        int24 indexed tickUpper,\n        uint128 amount0,\n        uint128 amount1\n    );\n\n    /// @notice Emitted when a position's liquidity is removed\n    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect\n    /// @param owner The owner of the position for which liquidity is removed\n    /// @param tickLower The lower tick of the position\n    /// @param tickUpper The upper tick of the position\n    /// @param amount The amount of liquidity to remove\n    /// @param amount0 The amount of token0 withdrawn\n    /// @param amount1 The amount of token1 withdrawn\n    event Burn(\n        address indexed owner,\n        int24 indexed tickLower,\n        int24 indexed tickUpper,\n        uint128 amount,\n        uint256 amount0,\n        uint256 amount1\n    );\n\n    /// @notice Emitted by the pool for any swaps between token0 and token1\n    /// @param sender The address that initiated the swap call, and that received the callback\n    /// @param recipient The address that received the output of the swap\n    /// @param amount0 The delta of the token0 balance of the pool\n    /// @param amount1 The delta of the token1 balance of the pool\n    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96\n    /// @param liquidity The liquidity of the pool after the swap\n    /// @param tick The log base 1.0001 of price of the pool after the swap\n    event Swap(\n        address indexed sender,\n        address indexed recipient,\n        int256 amount0,\n        int256 amount1,\n        uint160 sqrtPriceX96,\n        uint128 liquidity,\n        int24 tick\n    );\n\n    /// @notice Emitted by the pool for any flashes of token0/token1\n    /// @param sender The address that initiated the swap call, and that received the callback\n    /// @param recipient The address that received the tokens from flash\n    /// @param amount0 The amount of token0 that was flashed\n    /// @param amount1 The amount of token1 that was flashed\n    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee\n    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee\n    event Flash(\n        address indexed sender,\n        address indexed recipient,\n        uint256 amount0,\n        uint256 amount1,\n        uint256 paid0,\n        uint256 paid1\n    );\n\n    /// @notice Emitted by the pool for increases to the number of observations that can be stored\n    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index\n    /// just before a mint/swap/burn.\n    /// @param observationCardinalityNextOld The previous value of the next observation cardinality\n    /// @param observationCardinalityNextNew The updated value of the next observation cardinality\n    event IncreaseObservationCardinalityNext(\n        uint16 observationCardinalityNextOld,\n        uint16 observationCardinalityNextNew\n    );\n\n    /// @notice Emitted when the protocol fee is changed by the pool\n    /// @param feeProtocol0Old The previous value of the token0 protocol fee\n    /// @param feeProtocol1Old The previous value of the token1 protocol fee\n    /// @param feeProtocol0New The updated value of the token0 protocol fee\n    /// @param feeProtocol1New The updated value of the token1 protocol fee\n    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);\n\n    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner\n    /// @param sender The address that collects the protocol fees\n    /// @param recipient The address that receives the collected protocol fees\n    /// @param amount0 The amount of token0 protocol fees that is withdrawn\n    /// @param amount0 The amount of token1 protocol fees that is withdrawn\n    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);\n}\n"
      },
      "@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolImmutables.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that never changes\n/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values\ninterface IUniswapV3PoolImmutables {\n    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface\n    /// @return The contract address\n    function factory() external view returns (address);\n\n    /// @notice The first of the two tokens of the pool, sorted by address\n    /// @return The token contract address\n    function token0() external view returns (address);\n\n    /// @notice The second of the two tokens of the pool, sorted by address\n    /// @return The token contract address\n    function token1() external view returns (address);\n\n    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6\n    /// @return The fee\n    function fee() external view returns (uint24);\n\n    /// @notice The pool tick spacing\n    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive\n    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...\n    /// This value is an int24 to avoid casting even though it is always positive.\n    /// @return The tick spacing\n    function tickSpacing() external view returns (int24);\n\n    /// @notice The maximum amount of position liquidity that can use any tick in the range\n    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and\n    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool\n    /// @return The max amount of liquidity per tick\n    function maxLiquidityPerTick() external view returns (uint128);\n}\n"
      },
      "@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissioned pool actions\n/// @notice Contains pool methods that may only be called by the factory owner\ninterface IUniswapV3PoolOwnerActions {\n    /// @notice Set the denominator of the protocol's % share of the fees\n    /// @param feeProtocol0 new protocol fee for token0 of the pool\n    /// @param feeProtocol1 new protocol fee for token1 of the pool\n    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;\n\n    /// @notice Collect the protocol fee accrued to the pool\n    /// @param recipient The address to which collected protocol fees should be sent\n    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1\n    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0\n    /// @return amount0 The protocol fee collected in token0\n    /// @return amount1 The protocol fee collected in token1\n    function collectProtocol(\n        address recipient,\n        uint128 amount0Requested,\n        uint128 amount1Requested\n    ) external returns (uint128 amount0, uint128 amount1);\n}\n"
      },
      "@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolState.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that can change\n/// @notice These methods compose the pool's state, and can change with any frequency including multiple times\n/// per transaction\ninterface IUniswapV3PoolState {\n    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas\n    /// when accessed externally.\n    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value\n    /// tick The current tick of the pool, i.e. according to the last tick transition that was run.\n    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick\n    /// boundary.\n    /// observationIndex The index of the last oracle observation that was written,\n    /// observationCardinality The current maximum number of observations stored in the pool,\n    /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.\n    /// feeProtocol The protocol fee for both tokens of the pool.\n    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0\n    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.\n    /// unlocked Whether the pool is currently locked to reentrancy\n    function slot0()\n        external\n        view\n        returns (\n            uint160 sqrtPriceX96,\n            int24 tick,\n            uint16 observationIndex,\n            uint16 observationCardinality,\n            uint16 observationCardinalityNext,\n            uint8 feeProtocol,\n            bool unlocked\n        );\n\n    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool\n    /// @dev This value can overflow the uint256\n    function feeGrowthGlobal0X128() external view returns (uint256);\n\n    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool\n    /// @dev This value can overflow the uint256\n    function feeGrowthGlobal1X128() external view returns (uint256);\n\n    /// @notice The amounts of token0 and token1 that are owed to the protocol\n    /// @dev Protocol fees will never exceed uint128 max in either token\n    function protocolFees() external view returns (uint128 token0, uint128 token1);\n\n    /// @notice The currently in range liquidity available to the pool\n    /// @dev This value has no relationship to the total liquidity across all ticks\n    function liquidity() external view returns (uint128);\n\n    /// @notice Look up information about a specific tick in the pool\n    /// @param tick The tick to look up\n    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or\n    /// tick upper,\n    /// liquidityNet how much liquidity changes when the pool price crosses the tick,\n    /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,\n    /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,\n    /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick\n    /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,\n    /// secondsOutside the seconds spent on the other side of the tick from the current tick,\n    /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.\n    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.\n    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for\n    /// a specific position.\n    function ticks(int24 tick)\n        external\n        view\n        returns (\n            uint128 liquidityGross,\n            int128 liquidityNet,\n            uint256 feeGrowthOutside0X128,\n            uint256 feeGrowthOutside1X128,\n            int56 tickCumulativeOutside,\n            uint160 secondsPerLiquidityOutsideX128,\n            uint32 secondsOutside,\n            bool initialized\n        );\n\n    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information\n    function tickBitmap(int16 wordPosition) external view returns (uint256);\n\n    /// @notice Returns the information about a position by the position's key\n    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper\n    /// @return _liquidity The amount of liquidity in the position,\n    /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,\n    /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,\n    /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,\n    /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke\n    function positions(bytes32 key)\n        external\n        view\n        returns (\n            uint128 _liquidity,\n            uint256 feeGrowthInside0LastX128,\n            uint256 feeGrowthInside1LastX128,\n            uint128 tokensOwed0,\n            uint128 tokensOwed1\n        );\n\n    /// @notice Returns data about a specific observation index\n    /// @param index The element of the observations array to fetch\n    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time\n    /// ago, rather than at a specific index in the array.\n    /// @return blockTimestamp The timestamp of the observation,\n    /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,\n    /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,\n    /// Returns initialized whether the observation has been initialized and the values are safe to use\n    function observations(uint256 index)\n        external\n        view\n        returns (\n            uint32 blockTimestamp,\n            int56 tickCumulative,\n            uint160 secondsPerLiquidityCumulativeX128,\n            bool initialized\n        );\n}\n"
      },
      "@uniswap/v3-core/contracts/libraries/FullMath.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.4.0 <0.8.0;\n\n/// @title Contains 512-bit math functions\n/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision\n/// @dev Handles \"phantom overflow\" i.e., allows multiplication and division where an intermediate value overflows 256 bits\nlibrary FullMath {\n    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n    /// @param a The multiplicand\n    /// @param b The multiplier\n    /// @param denominator The divisor\n    /// @return result The 256-bit result\n    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv\n    function mulDiv(\n        uint256 a,\n        uint256 b,\n        uint256 denominator\n    ) internal pure returns (uint256 result) {\n        // 512-bit multiply [prod1 prod0] = a * b\n        // Compute the product mod 2**256 and mod 2**256 - 1\n        // then use the Chinese Remainder Theorem to reconstruct\n        // 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(a, b, not(0))\n            prod0 := mul(a, b)\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            require(denominator > 0);\n            assembly {\n                result := div(prod0, denominator)\n            }\n            return result;\n        }\n\n        // Make sure the result is less than 2**256.\n        // Also prevents denominator == 0\n        require(denominator > prod1);\n\n        ///////////////////////////////////////////////\n        // 512 by 256 division.\n        ///////////////////////////////////////////////\n\n        // Make division exact by subtracting the remainder from [prod1 prod0]\n        // Compute remainder using mulmod\n        uint256 remainder;\n        assembly {\n            remainder := mulmod(a, b, denominator)\n        }\n        // Subtract 256 bit number from 512 bit number\n        assembly {\n            prod1 := sub(prod1, gt(remainder, prod0))\n            prod0 := sub(prod0, remainder)\n        }\n\n        // Factor powers of two out of denominator\n        // Compute largest power of two divisor of denominator.\n        // Always >= 1.\n        uint256 twos = -denominator & denominator;\n        // Divide denominator by power of two\n        assembly {\n            denominator := div(denominator, twos)\n        }\n\n        // Divide [prod1 prod0] by the factors of two\n        assembly {\n            prod0 := div(prod0, twos)\n        }\n        // Shift in bits from prod1 into prod0. For this we need\n        // to flip `twos` such that it is 2**256 / twos.\n        // If twos is zero, then it becomes one\n        assembly {\n            twos := add(div(sub(0, twos), twos), 1)\n        }\n        prod0 |= prod1 * twos;\n\n        // Invert denominator mod 2**256\n        // Now that denominator is an odd number, it has an inverse\n        // modulo 2**256 such that denominator * inv = 1 mod 2**256.\n        // Compute the inverse by starting with a seed that is correct\n        // correct for four bits. That is, denominator * inv = 1 mod 2**4\n        uint256 inv = (3 * denominator) ^ 2;\n        // Now use Newton-Raphson iteration to improve the precision.\n        // Thanks to Hensel's lifting lemma, this also works in modular\n        // arithmetic, doubling the correct bits in each step.\n        inv *= 2 - denominator * inv; // inverse mod 2**8\n        inv *= 2 - denominator * inv; // inverse mod 2**16\n        inv *= 2 - denominator * inv; // inverse mod 2**32\n        inv *= 2 - denominator * inv; // inverse mod 2**64\n        inv *= 2 - denominator * inv; // inverse mod 2**128\n        inv *= 2 - denominator * inv; // inverse mod 2**256\n\n        // Because the division is now exact we can divide by multiplying\n        // with the modular inverse of denominator. This will give us the\n        // correct result modulo 2**256. Since the precoditions guarantee\n        // that the outcome is less than 2**256, this is the final result.\n        // We don't need to compute the high bits of the result and prod1\n        // is no longer required.\n        result = prod0 * inv;\n        return result;\n    }\n\n    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n    /// @param a The multiplicand\n    /// @param b The multiplier\n    /// @param denominator The divisor\n    /// @return result The 256-bit result\n    function mulDivRoundingUp(\n        uint256 a,\n        uint256 b,\n        uint256 denominator\n    ) internal pure returns (uint256 result) {\n        result = mulDiv(a, b, denominator);\n        if (mulmod(a, b, denominator) > 0) {\n            require(result < type(uint256).max);\n            result++;\n        }\n    }\n}\n"
      },
      "@uniswap/v3-core/contracts/libraries/TickMath.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0 <0.8.0;\n\n/// @title Math library for computing sqrt prices from ticks and vice versa\n/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports\n/// prices between 2**-128 and 2**128\nlibrary TickMath {\n    /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128\n    int24 internal constant MIN_TICK = -887272;\n    /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128\n    int24 internal constant MAX_TICK = -MIN_TICK;\n\n    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)\n    uint160 internal constant MIN_SQRT_RATIO = 4295128739;\n    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)\n    uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;\n\n    /// @notice Calculates sqrt(1.0001^tick) * 2^96\n    /// @dev Throws if |tick| > max tick\n    /// @param tick The input tick for the above formula\n    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)\n    /// at the given tick\n    function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {\n        uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));\n        require(absTick <= uint256(MAX_TICK), 'T');\n\n        uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;\n        if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;\n        if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;\n        if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;\n        if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;\n        if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;\n        if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;\n        if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;\n        if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;\n        if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;\n        if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;\n        if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;\n        if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;\n        if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;\n        if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;\n        if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;\n        if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;\n        if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;\n        if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;\n        if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;\n\n        if (tick > 0) ratio = type(uint256).max / ratio;\n\n        // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.\n        // we then downcast because we know the result always fits within 160 bits due to our tick input constraint\n        // we round up in the division so getTickAtSqrtRatio of the output price is always consistent\n        sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));\n    }\n\n    /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio\n    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may\n    /// ever return.\n    /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96\n    /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio\n    function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {\n        // second inequality must be < because the price can never reach the price at the max tick\n        require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');\n        uint256 ratio = uint256(sqrtPriceX96) << 32;\n\n        uint256 r = ratio;\n        uint256 msb = 0;\n\n        assembly {\n            let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))\n            msb := or(msb, f)\n            r := shr(f, r)\n        }\n        assembly {\n            let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))\n            msb := or(msb, f)\n            r := shr(f, r)\n        }\n        assembly {\n            let f := shl(5, gt(r, 0xFFFFFFFF))\n            msb := or(msb, f)\n            r := shr(f, r)\n        }\n        assembly {\n            let f := shl(4, gt(r, 0xFFFF))\n            msb := or(msb, f)\n            r := shr(f, r)\n        }\n        assembly {\n            let f := shl(3, gt(r, 0xFF))\n            msb := or(msb, f)\n            r := shr(f, r)\n        }\n        assembly {\n            let f := shl(2, gt(r, 0xF))\n            msb := or(msb, f)\n            r := shr(f, r)\n        }\n        assembly {\n            let f := shl(1, gt(r, 0x3))\n            msb := or(msb, f)\n            r := shr(f, r)\n        }\n        assembly {\n            let f := gt(r, 0x1)\n            msb := or(msb, f)\n        }\n\n        if (msb >= 128) r = ratio >> (msb - 127);\n        else r = ratio << (127 - msb);\n\n        int256 log_2 = (int256(msb) - 128) << 64;\n\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(63, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(62, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(61, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(60, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(59, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(58, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(57, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(56, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(55, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(54, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(53, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(52, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(51, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(50, f))\n        }\n\n        int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number\n\n        int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);\n        int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);\n\n        tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;\n    }\n}\n"
      },
      "@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0 <0.8.0;\n\nimport '@uniswap/v3-core/contracts/libraries/FullMath.sol';\nimport '@uniswap/v3-core/contracts/libraries/TickMath.sol';\nimport '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';\n\n/// @title Oracle library\n/// @notice Provides functions to integrate with V3 pool oracle\nlibrary OracleLibrary {\n    /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool\n    /// @param pool Address of the pool that we want to observe\n    /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means\n    /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp\n    /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp\n    function consult(address pool, uint32 secondsAgo)\n        internal\n        view\n        returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)\n    {\n        require(secondsAgo != 0, 'BP');\n\n        uint32[] memory secondsAgos = new uint32[](2);\n        secondsAgos[0] = secondsAgo;\n        secondsAgos[1] = 0;\n\n        (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =\n            IUniswapV3Pool(pool).observe(secondsAgos);\n\n        int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];\n        uint160 secondsPerLiquidityCumulativesDelta =\n            secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];\n\n        arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgo);\n        // Always round to negative infinity\n        if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgo != 0)) arithmeticMeanTick--;\n\n        // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128\n        uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;\n        harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));\n    }\n\n    /// @notice Given a tick and a token amount, calculates the amount of token received in exchange\n    /// @param tick Tick value used to calculate the quote\n    /// @param baseAmount Amount of token to be converted\n    /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination\n    /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination\n    /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken\n    function getQuoteAtTick(\n        int24 tick,\n        uint128 baseAmount,\n        address baseToken,\n        address quoteToken\n    ) internal pure returns (uint256 quoteAmount) {\n        uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);\n\n        // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself\n        if (sqrtRatioX96 <= type(uint128).max) {\n            uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;\n            quoteAmount = baseToken < quoteToken\n                ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)\n                : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);\n        } else {\n            uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);\n            quoteAmount = baseToken < quoteToken\n                ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)\n                : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);\n        }\n    }\n\n    /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation\n    /// @param pool Address of Uniswap V3 pool that we want to observe\n    /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool\n    function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {\n        (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n        require(observationCardinality > 0, 'NI');\n\n        (uint32 observationTimestamp, , , bool initialized) =\n            IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality);\n\n        // The next index might not be initialized if the cardinality is in the process of increasing\n        // In this case the oldest observation is always in index 0\n        if (!initialized) {\n            (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);\n        }\n\n        secondsAgo = uint32(block.timestamp) - observationTimestamp;\n    }\n\n    /// @notice Given a pool, it returns the tick value as of the start of the current block\n    /// @param pool Address of Uniswap V3 pool\n    /// @return The tick that the pool was in at the start of the current block\n    function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) {\n        (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n\n        // 2 observations are needed to reliably calculate the block starting tick\n        require(observationCardinality > 1, 'NEO');\n\n        // If the latest observation occurred in the past, then no tick-changing trades have happened in this block\n        // therefore the tick in `slot0` is the same as at the beginning of the current block.\n        // We don't need to check if this observation is initialized - it is guaranteed to be.\n        (uint32 observationTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, ) =\n            IUniswapV3Pool(pool).observations(observationIndex);\n        if (observationTimestamp != uint32(block.timestamp)) {\n            return (tick, IUniswapV3Pool(pool).liquidity());\n        }\n\n        uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;\n        (\n            uint32 prevObservationTimestamp,\n            int56 prevTickCumulative,\n            uint160 prevSecondsPerLiquidityCumulativeX128,\n            bool prevInitialized\n        ) = IUniswapV3Pool(pool).observations(prevIndex);\n\n        require(prevInitialized, 'ONI');\n\n        uint32 delta = observationTimestamp - prevObservationTimestamp;\n        tick = int24((tickCumulative - prevTickCumulative) / delta);\n        uint128 liquidity =\n            uint128(\n                (uint192(delta) * type(uint160).max) /\n                    (uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32)\n            );\n        return (tick, liquidity);\n    }\n\n    /// @notice Information for calculating a weighted arithmetic mean tick\n    struct WeightedTickData {\n        int24 tick;\n        uint128 weight;\n    }\n\n    /// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick\n    /// @param weightedTickData An array of ticks and weights\n    /// @return weightedArithmeticMeanTick The weighted arithmetic mean tick\n    /// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not,\n    /// extreme care must be taken to ensure that ticks are comparable (including decimal differences).\n    /// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price.\n    function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData)\n        internal\n        pure\n        returns (int24 weightedArithmeticMeanTick)\n    {\n        // Accumulates the sum of products between each tick and its weight\n        int256 numerator;\n\n        // Accumulates the sum of the weights\n        uint256 denominator;\n\n        // Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic\n        for (uint256 i; i < weightedTickData.length; i++) {\n            numerator += weightedTickData[i].tick * int256(weightedTickData[i].weight);\n            denominator += weightedTickData[i].weight;\n        }\n\n        weightedArithmeticMeanTick = int24(numerator / int256(denominator));\n        // Always round to negative infinity\n        if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--;\n    }\n\n    /// @notice Returns the \"synthetic\" tick which represents the price of the first entry in `tokens` in terms of the last\n    /// @dev Useful for calculating relative prices along routes.\n    /// @dev There must be one tick for each pairwise set of tokens.\n    /// @param tokens The token contract addresses\n    /// @param ticks The ticks, representing the price of each token pair in `tokens`\n    /// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens`\n    function getChainedPrice(address[] memory tokens, int24[] memory ticks)\n        internal\n        pure\n        returns (int256 syntheticTick)\n    {\n        require(tokens.length - 1 == ticks.length, 'DL');\n        for (uint256 i = 1; i <= ticks.length; i++) {\n            // check the tokens for address sort order, then accumulate the\n            // ticks into the running synthetic tick, ensuring that intermediate tokens \"cancel out\"\n            tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1];\n        }\n    }\n}\n"
      },
      "contracts/beanstalk/AppStorage.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport \"../interfaces/IDiamondCut.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/utils/Counters.sol\";\n\n/**\n * @title Account\n * @author Publius\n * @notice Stores Farmer-level Beanstalk state.\n * @dev {Account.State} is the primary struct that is referenced from {Storage.State}. \n * All other structs in {Account} are referenced in {Account.State}. Each unique\n * Ethereum address is a Farmer.\n */\ncontract Account {\n    /**\n     * @notice Stores a Farmer's Plots and Pod allowances.\n     * @param plots A Farmer's Plots. Maps from Plot index to Pod amount.\n     * @param podAllowances An allowance mapping for Pods similar to that of the ERC-20 standard. Maps from spender address to allowance amount.\n     */\n    struct Field {\n        mapping(uint256 => uint256) plots;\n        mapping(address => uint256) podAllowances;\n    }\n\n    /**\n     * @notice Stores a Farmer's Deposits and Seeds per Deposit, and formerly stored Withdrawals.\n     * @param withdrawals DEPRECATED: Silo V1 Withdrawals are no longer referenced.\n     * @param deposits Unripe Bean/LP Deposits (previously Bean/LP Deposits).\n     * @param depositSeeds BDV of Unripe LP Deposits / 4 (previously # of Seeds in corresponding LP Deposit).\n     */\n    struct AssetSilo {\n        mapping(uint32 => uint256) withdrawals;\n        mapping(uint32 => uint256) deposits;\n        mapping(uint32 => uint256) depositSeeds;\n    }\n\n    /**\n     * @notice Represents a Deposit of a given Token in the Silo at a given Season.\n     * @param amount The amount of Tokens in the Deposit.\n     * @param bdv The Bean-denominated value of the total amount of Tokens in the Deposit.\n     * @dev `amount` and `bdv` are packed as uint128 to save gas.\n     */\n    struct Deposit {\n        uint128 amount; // ───┐ 16\n        uint128 bdv; // ──────┘ 16 (32/32)\n    }\n\n    /**\n     * @notice Stores a Farmer's Stalk and Seeds balances.\n     * @param stalk Balance of the Farmer's Stalk.\n     * @param seeds DEPRECATED – Balance of the Farmer's Seeds. Seeds are no longer referenced as of Silo V3.\n     */\n    struct Silo {\n        uint256 stalk;\n        uint256 seeds;\n    }\n    \n    /**\n     * @notice Stores a Farmer's germinating stalk.\n     * @param odd - stalk from assets deposited in odd seasons.\n     * @param even - stalk from assets deposited in even seasons.\n     */\n    struct FarmerGerminatingStalk {\n        uint128 odd;\n        uint128 even;\n    }\n    \n    /**\n     * @notice This struct stores the mow status for each Silo-able token, for each farmer. \n     * This gets updated each time a farmer mows, or adds/removes deposits.\n     * @param lastStem The last cumulative grown stalk per bdv index at which the farmer mowed.\n     * @param bdv The bdv of all of a farmer's deposits of this token type.\n     * \n     */\n    struct MowStatus {\n        int96 lastStem; // ───┐ 12\n        uint128 bdv; // ──────┘ 16 (28/32)\n    }\n\n    /**\n     * @notice Stores a Farmer's Season of Plenty (SOP) balances.\n     * @param roots The number of Roots a Farmer had when it started Raining.\n     * @param plentyPerRoot The global Plenty Per Root index at the last time a Farmer updated their Silo.\n     * @param plenty The balance of a Farmer's plenty. Plenty can be claimed directly for 3CRV.\n     */\n    struct SeasonOfPlenty {\n        uint256 roots;\n        uint256 plentyPerRoot;\n        uint256 plenty;\n    }\n    \n    /**\n     * @notice Defines the state object for a Farmer.\n     * @param field A Farmer's Field storage.\n     * @param bean A Farmer's Unripe Bean Deposits only as a result of Replant (previously held the V1 Silo Deposits/Withdrawals for Beans).\n     * @param lp A Farmer's Unripe LP Deposits as a result of Replant of BEAN:ETH Uniswap v2 LP Tokens (previously held the V1 Silo Deposits/Withdrawals for BEAN:ETH Uniswap v2 LP Tokens).\n     * @param s A Farmer's Silo storage.\n     * @param deprecated_votedUntil DEPRECATED – Replant removed on-chain governance including the ability to vote on BIPs.\n     * @param lastUpdate The Season in which the Farmer last updated their Silo.\n     * @param lastSop The last Season that a SOP occured at the time the Farmer last updated their Silo.\n     * @param lastRain The last Season that it started Raining at the time the Farmer last updated their Silo.\n     * @param deprecated_deltaRoots DEPRECATED – BIP-39 introduced germination.\n     * @param deprecated_lastSIs DEPRECATED – In Silo V1.2, the Silo reward mechanism was updated to no longer need to store the number of the Supply Increases at the time the Farmer last updated their Silo.\n     * @param deprecated_proposedUntil DEPRECATED – Replant removed on-chain governance including the ability to propose BIPs.\n     * @param deprecated_sop DEPRECATED – Replant reset the Season of Plenty mechanism\n     * @param roots A Farmer's Root balance.\n     * @param deprecated_wrappedBeans DEPRECATED – Replant generalized Internal Balances. Wrapped Beans are now stored at the AppStorage level.\n     * @param legacyV2Deposits DEPRECATED - SiloV2 was retired in favor of Silo V3. A Farmer's Silo Deposits stored as a map from Token address to Season of Deposit to Deposit.\n     * @param withdrawals Withdraws were removed in zero withdraw upgrade - A Farmer's Withdrawals from the Silo stored as a map from Token address to Season the Withdrawal becomes Claimable to Withdrawn amount of Tokens.\n     * @param sop A Farmer's Season of Plenty storage.\n     * @param depositAllowances A mapping of `spender => Silo token address => amount`.\n     * @param tokenAllowances Internal balance token allowances.\n     * @param depositPermitNonces A Farmer's current deposit permit nonce\n     * @param tokenPermitNonces A Farmer's current token permit nonce\n     * @param legacyV3Deposits DEPRECATED: Silo V3 deposits. Deprecated in favor of SiloV3.1 mapping from depositId to Deposit.\n     * @param mowStatuses A mapping of Silo-able token address to MowStatus.\n     * @param isApprovedForAll A mapping of ERC1155 operator to approved status. ERC1155 compatability.\n     * @param farmerGerminating A Farmer's germinating stalk. Seperated into odd and even stalk.\n     * @param deposits SiloV3.1 deposits. A mapping from depositId to Deposit. SiloV3.1 introduces greater precision for deposits.\n     */\n    struct State {\n        Field field; // A Farmer's Field storage.\n\n        /*\n         * @dev (Silo V1) A Farmer's Unripe Bean Deposits only as a result of Replant\n         *\n         * Previously held the V1 Silo Deposits/Withdrawals for Beans.\n\n         * NOTE: While the Silo V1 format is now deprecated, this storage slot is used for gas\n         * efficiency to store Unripe BEAN deposits. See {LibUnripeSilo} for more.\n         */\n        AssetSilo bean; \n\n        /*\n         * @dev (Silo V1) Unripe LP Deposits as a result of Replant.\n         * \n         * Previously held the V1 Silo Deposits/Withdrawals for BEAN:ETH Uniswap v2 LP Tokens.\n         * \n         * BEAN:3CRV and BEAN:LUSD tokens prior to Replant were stored in the Silo V2\n         * format in the `s.a[account].legacyV2Deposits` mapping.\n         *\n         * NOTE: While the Silo V1 format is now deprecated, unmigrated Silo V1 deposits are still\n         * stored in this storage slot. See {LibUnripeSilo} for more.\n         * \n         */\n        AssetSilo lp; \n\n        /*\n         * @dev Holds Silo specific state for each account.\n         */\n        Silo s;\n        \n        uint32 votedUntil; // DEPRECATED – Replant removed on-chain governance including the ability to vote on BIPs.\n        uint32 lastUpdate; // The Season in which the Farmer last updated their Silo.\n        uint32 lastSop; // The last Season that a SOP occured at the time the Farmer last updated their Silo.\n        uint32 lastRain; // The last Season that it started Raining at the time the Farmer last updated their Silo.\n        uint128 deprecated_deltaRoots; // DEPRECATED - BIP-39 introduced germination. \n        SeasonOfPlenty deprecated; // DEPRECATED – Replant reset the Season of Plenty mechanism\n        uint256 roots; // A Farmer's Root balance.\n        uint256 deprecated_wrappedBeans; // DEPRECATED – Replant generalized Internal Balances. Wrapped Beans are now stored at the AppStorage level.\n        mapping(address => mapping(uint32 => Deposit)) legacyV2Deposits; // Legacy Silo V2 Deposits stored as a map from Token address to Season of Deposit to Deposit. NOTE: While the Silo V2 format is now deprecated, unmigrated Silo V2 deposits are still stored in this mapping.\n        mapping(address => mapping(uint32 => uint256)) withdrawals; // Zero withdraw eliminates a need for withdraw mapping, but is kept for legacy\n        SeasonOfPlenty sop; // A Farmer's Season Of Plenty storage.\n        mapping(address => mapping(address => uint256)) depositAllowances; // Spender => Silo Token\n        mapping(address => mapping(IERC20 => uint256)) tokenAllowances; // Token allowances\n        uint256 depositPermitNonces; // A Farmer's current deposit permit nonce\n        uint256 tokenPermitNonces; // A Farmer's current token permit nonce\n        mapping(uint256 => Deposit) legacyV3Deposits; // NOTE: Legacy SiloV3 Deposits stored as a map from uint256 to Deposit. This is an concat of the token address and the CGSPBDV for a ERC20 deposit.\n        mapping(address => MowStatus) mowStatuses; // Store a MowStatus for each Whitelisted Silo token\n        mapping(address => bool) isApprovedForAll; // ERC1155 isApprovedForAll mapping \n        \n        // Germination\n        FarmerGerminatingStalk farmerGerminating; // A Farmer's germinating stalk.\n\n        // Silo v3.1\n        mapping(uint256 => Deposit) deposits; // Silo v3.1 Deposits stored as a map from uint256 to Deposit. This is an concat of the token address and the stem for a ERC20 deposit.\n    }\n}\n\n/**\n * @title Storage\n * @author Publius\n * @notice Stores system-level Beanstalk state.\n */\ncontract Storage {\n    /**\n     * @notice DEPRECATED: System-level contract addresses.\n     * @dev After Replant, Beanstalk stores Token addresses as constants to save gas.\n     */\n    struct Contracts {\n        address bean;\n        address pair;\n        address pegPair;\n        address weth;\n    }\n\n    /**\n     * @notice System-level Field state variables.\n     * @param soil The number of Soil currently available. Adjusted during {Sun.stepSun}.\n     * @param beanSown The number of Bean sown within the current Season. Reset during {Weather.calcCaseId}.\n     * @param pods The pod index; the total number of Pods ever minted.\n     * @param harvested The harvested index; the total number of Pods that have ever been Harvested.\n     * @param harvestable The harvestable index; the total number of Pods that have ever been Harvestable. Included previously Harvested Beans.\n     */\n    struct Field {\n        uint128 soil; // ──────┐ 16\n        uint128 beanSown; // ──┘ 16 (32/32)\n        uint256 pods;\n        uint256 harvested;\n        uint256 harvestable;\n    }\n\n    /**\n     * @notice DEPRECATED: Contained data about each BIP (Beanstalk Improvement Proposal).\n     * @dev Replant moved governance off-chain. This struct is left for future reference.\n     * \n     */\n    struct Bip {\n        address proposer; // ───┐ 20\n        uint32 start; //        │ 4 (24)\n        uint32 period; //       │ 4 (28)\n        bool executed; // ──────┘ 1 (29/32)\n        int pauseOrUnpause; \n        uint128 timestamp;\n        uint256 roots;\n        uint256 endTotalRoots;\n    }\n\n    /**\n     * @notice DEPRECATED: Contained data for the DiamondCut associated with each BIP.\n     * @dev Replant moved governance off-chain. This struct is left for future reference.\n     * @dev {Storage.DiamondCut} stored DiamondCut-related data for each {Bip}.\n     */\n    struct DiamondCut {\n        IDiamondCut.FacetCut[] diamondCut;\n        address initAddress;\n        bytes initData;\n    }\n\n    /**\n     * @notice DEPRECATED: Contained all governance-related data, including a list of BIPs, votes for each BIP, and the DiamondCut needed to execute each BIP.\n     * @dev Replant moved governance off-chain. This struct is left for future reference.\n     * @dev {Storage.Governance} stored all BIPs and Farmer voting information.\n     */\n    struct Governance {\n        uint32[] activeBips;\n        uint32 bipIndex;\n        mapping(uint32 => DiamondCut) diamondCuts;\n        mapping(uint32 => mapping(address => bool)) voted;\n        mapping(uint32 => Bip) bips;\n    }\n\n    /**\n     * @notice System-level Silo state; contains deposit and withdrawal data for a particular whitelisted Token.\n     * @param deposited The total amount of this Token currently Deposited in the Silo.\n     * @param depositedBdv The total bdv of this Token currently Deposited in the Silo.\n     * @param withdrawn The total amount of this Token currently Withdrawn From the Silo.\n     * @dev {Storage.State} contains a mapping from Token address => AssetSilo.\n     * Currently, the bdv of deposits are asynchronous, and require an on-chain transaction to update.\n     * Thus, the total bdv of deposits cannot be calculated, and must be stored and updated upon a bdv change.\n     * \n     * \n     * Note that \"Withdrawn\" refers to the amount of Tokens that have been Withdrawn\n     * but not yet Claimed. This will be removed in a future BIP.\n     */\n    struct AssetSilo {\n        uint128 deposited;\n        uint128 depositedBdv;\n        uint256 withdrawn;\n    }\n\n    /**\n     * @notice Whitelist Status a token that has been Whitelisted before.\n     * @param token the address of the token.\n     * @param a whether the address is whitelisted.\n     * @param isWhitelistedLp whether the address is a whitelisted LP token.\n     * @param isWhitelistedWell whether the address is a whitelisted Well token.\n     */\n\n    struct WhitelistStatus {\n        address token;\n        bool isWhitelisted;\n        bool isWhitelistedLp;\n        bool isWhitelistedWell;\n    }\n\n    /**\n     * @notice System-level Silo state variables.\n     * @param stalk The total amount of active Stalk (including Earned Stalk, excluding Grown Stalk).\n     * @param deprecated_seeds DEPRECATED: The total amount of active Seeds (excluding Earned Seeds).\n     * @dev seeds are no longer used internally. Balance is wiped to 0 from the mayflower update. see {mowAndMigrate}.\n     * @param roots The total amount of Roots.\n     */\n    struct Silo {\n        uint256 stalk;\n        uint256 deprecated_seeds; \n        uint256 roots;\n    }\n\n    /**\n     * @notice System-level Curve Metapool Oracle state variables.\n     * @param initialized True if the Oracle has been initialzed. It needs to be initialized on Deployment and re-initialized each Unpause.\n     * @param startSeason The Season the Oracle started minting. Used to ramp up delta b when oracle is first added.\n     * @param balances The cumulative reserve balances of the pool at the start of the Season (used for computing time weighted average delta b).\n     * @param timestamp DEPRECATED: The timestamp of the start of the current Season. `LibCurveMinting` now uses `s.season.timestamp` instead of storing its own for gas efficiency purposes.\n     * @dev Currently refers to the time weighted average deltaB calculated from the BEAN:3CRV pool.\n     */\n    struct CurveMetapoolOracle {\n        bool initialized; // ────┐ 1\n        uint32 startSeason; // ──┘ 4 (5/32)\n        uint256[2] balances;\n        uint256 timestamp;\n    }\n\n    /**\n     * @notice System-level Rain balances. Rain occurs when P > 1 and the Pod Rate Excessively Low.\n     * @dev The `raining` storage variable is stored in the Season section for a gas efficient read operation.\n     * @param deprecated Previously held Rain start and Rain status variables. Now moved to Season struct for gas efficiency.\n     * @param pods The number of Pods when it last started Raining.\n     * @param roots The number of Roots when it last started Raining.\n     */\n    struct Rain {\n        uint256 deprecated;\n        uint256 pods;\n        uint256 roots;\n    }\n\n    /**\n     * @notice System-level Season state variables.\n     * @param current The current Season in Beanstalk.\n     * @param lastSop The Season in which the most recent consecutive series of Seasons of Plenty started.\n     * @param withdrawSeasons The number of Seasons required to Withdraw a Deposit.\n     * @param lastSopSeason The Season in which the most recent consecutive series of Seasons of Plenty ended.\n     * @param rainStart Stores the most recent Season in which Rain started.\n     * @param raining True if it is Raining (P > 1, Pod Rate Excessively Low).\n     * @param fertilizing True if Beanstalk has Fertilizer left to be paid off.\n     * @param sunriseBlock The block of the start of the current Season.\n     * @param abovePeg Boolean indicating whether the previous Season was above or below peg.\n     * @param stemStartSeason // season in which the stem storage method was introduced.\n     * @param stemScaleSeason // season in which the stem v1.1 was introduced, where stems are not truncated anymore.\n     * This allows for greater precision of stems, and requires a soft migration (see {LibTokenSilo.removeDepositFromAccount})\n     * @param start The timestamp of the Beanstalk deployment rounded down to the nearest hour.\n     * @param period The length of each season in Beanstalk in seconds.\n     * @param timestamp The timestamp of the start of the current Season.\n     */\n    struct Season {\n        uint32 current; // ─────────────────┐ 4  \n        uint32 lastSop; //                  │ 4 (8)\n        uint8 withdrawSeasons; //           │ 1 (9)\n        uint32 lastSopSeason; //            │ 4 (13)\n        uint32 rainStart; //                │ 4 (17)\n        bool raining; //                    │ 1 (18)\n        bool fertilizing; //                │ 1 (19)\n        uint32 sunriseBlock; //             │ 4 (23)\n        bool abovePeg; //                   | 1 (24)\n        uint16 stemStartSeason; //          | 2 (26)\n        uint16 stemScaleSeason; //──────────┘ 2 (28/32)\n        uint256 start;\n        uint256 period;\n        uint256 timestamp;\n    }\n\n    /**\n     * @notice System-level Weather state variables.\n     * @param deprecated 2 slots that were previously used.\n     * @param lastDSoil Delta Soil; the number of Soil purchased last Season.\n     * @param lastSowTime The number of seconds it for Soil to sell out last Season.\n     * @param thisSowTime The number of seconds it for Soil to sell out this Season.\n     * @param t The Temperature; the maximum interest rate during the current Season for sowing Beans in Soil. Adjusted each Season.\n     */\n    struct Weather {\n        uint256[2] deprecated;\n        uint128 lastDSoil;  // ───┐ 16 (16)\n        uint32 lastSowTime; //    │ 4  (20)\n        uint32 thisSowTime; //    │ 4  (24)\n        uint32 t; // ─────────────┘ 4  (28/32)\n    }\n\n    /**\n     * @notice Describes a Fundraiser.\n     * @param payee The address to be paid after the Fundraiser has been fully funded.\n     * @param token The token address that used to raise funds for the Fundraiser.\n     * @param total The total number of Tokens that need to be raised to complete the Fundraiser.\n     * @param remaining The remaining number of Tokens that need to to complete the Fundraiser.\n     * @param start The timestamp at which the Fundraiser started (Fundraisers cannot be started and funded in the same block).\n     */\n    struct Fundraiser {\n        address payee;\n        address token;\n        uint256 total;\n        uint256 remaining;\n        uint256 start;\n    }\n\n    /**\n     * @notice Describes the settings for each Token that is Whitelisted in the Silo.\n     * @param selector The encoded BDV function selector for the token that pertains to \n     * an external view Beanstalk function with the following signature:\n     * ```\n     * function tokenToBdv(uint256 amount) external view returns (uint256);\n     * ```\n     * It is called by `LibTokenSilo` through the use of `delegatecall`\n     * to calculate a token's BDV at the time of Deposit.\n     * @param stalkEarnedPerSeason represents how much Stalk one BDV of the underlying deposited token\n     * grows each season. In the past, this was represented by seeds. This is stored as 1e6, plus stalk is stored\n     * as 1e10, so 1 legacy seed would be 1e6 * 1e10.\n     * @param stalkIssuedPerBdv The Stalk Per BDV that the Silo grants in exchange for Depositing this Token.\n     * previously called stalk.\n     * @param milestoneSeason The last season in which the stalkEarnedPerSeason for this token was updated.\n     * @param milestoneStem The cumulative amount of grown stalk per BDV for this token at the last stalkEarnedPerSeason update.\n     * @param encodeType determine the encoding type of the selector.\n     * a encodeType of 0x00 means the selector takes an input amount.\n     * 0x01 means the selector takes an input amount and a token.\n     * @param gpSelector The encoded gaugePoint function selector for the token that pertains to \n     * an external view Beanstalk function with the following signature:\n     * ```\n     * function gaugePoints(\n     *  uint256 currentGaugePoints,\n     *  uint256 optimalPercentDepositedBdv,\n     *  uint256 percentOfDepositedBdv\n     *  ) external view returns (uint256);\n     * ```\n     * @param lwSelector The encoded liquidityWeight function selector for the token that pertains to \n     * an external view Beanstalk function with the following signature `function liquidityWeight()`\n     * @param optimalPercentDepositedBdv The target percentage of the total LP deposited BDV for this token. 6 decimal precision.\n     * @param gaugePoints the amount of Gauge points this LP token has in the LP Gauge. Only used for LP whitelisted assets.\n     * GaugePoints has 18 decimal point precision (1 Gauge point = 1e18).\n\n     * @dev A Token is considered Whitelisted if there exists a non-zero {SiloSettings} selector.\n     */\n    struct SiloSettings {\n        bytes4 selector; // ────────────────────┐ 4\n        uint32 stalkEarnedPerSeason; //         │ 4  (8)\n        uint32 stalkIssuedPerBdv; //            │ 4  (12)\n        uint32 milestoneSeason; //              │ 4  (16)\n        int96 milestoneStem; //                 │ 12 (28)\n        bytes1 encodeType; //                   │ 1  (29)\n        int24 deltaStalkEarnedPerSeason; // ────┘ 3  (32)\n        bytes4 gpSelector; //    ────────────────┐ 4  \n        bytes4 lwSelector; //                    │ 4  (8)\n        uint128 gaugePoints; //                  │ 16 (24)\n        uint64 optimalPercentDepositedBdv; //  ──┘ 8  (32)\n    }\n\n    /**\n     * @notice Describes the settings for each Unripe Token in Beanstalk.\n     * @param underlyingToken The address of the Token underlying the Unripe Token.\n     * @param balanceOfUnderlying The number of Tokens underlying the Unripe Tokens (redemption pool).\n     * @param merkleRoot The Merkle Root used to validate a claim of Unripe Tokens.\n     * @dev An Unripe Token is a vesting Token that is redeemable for a a pro rata share\n     * of the `balanceOfUnderlying`, subject to a penalty based on the percent of\n     * Unfertilized Beans paid back.\n     * \n     * There were two Unripe Tokens added at Replant: \n     *  - Unripe Bean, with its `underlyingToken` as BEAN;\n     *  - Unripe LP, with its `underlyingToken` as BEAN:3CRV LP.\n     * \n     * Unripe Tokens are initially distributed through the use of a `merkleRoot`.\n     * \n     * The existence of a non-zero {UnripeSettings} implies that a Token is an Unripe Token.\n     */\n    struct UnripeSettings {\n        address underlyingToken;\n        uint256 balanceOfUnderlying;\n        bytes32 merkleRoot;\n    }\n\n    /**\n     * @notice System level variables used in the seed Gauge System.\n     * @param averageGrownStalkPerBdvPerSeason The average Grown Stalk Per BDV \n     * that beanstalk issues each season.\n     * @param beanToMaxLpGpPerBdvRatio a scalar of the gauge points(GP) per bdv \n     * issued to the largest LP share and Bean. 6 decimal precision.\n     * @dev a beanToMaxLpGpPerBdvRatio of 0 means LP should be incentivized the most,\n     * and that beans will have the minimum seeds ratio. see {LibGauge.getBeanToMaxLpGpPerBdvRatioScaled}\n     */\n    struct SeedGauge {\n        uint128 averageGrownStalkPerBdvPerSeason;\n        uint128 beanToMaxLpGpPerBdvRatio;\n    }\n\n    /**\n     * @notice Stores the twaReserves for each well during the sunrise function.\n     */\n    struct TwaReserves {\n        uint128 reserve0;\n        uint128 reserve1;\n    }\n\n    /**\n     * @notice Stores the total germination amounts for each whitelisted token.\n     */\n    struct Deposited {\n        uint128 amount;\n        uint128 bdv;\n    }\n\n    /** \n     * @notice Stores the system level germination data.\n     */\n    struct TotalGerminating {\n        mapping(address => Deposited) deposited;\n    }\n\n    struct Sr {\n\t    uint128 stalk;\n\t    uint128 roots;\n    }\n}\n\n/**\n * @title AppStorage\n * @author Publius\n * @notice Defines the state object for Beanstalk.\n * @param deprecated_index DEPRECATED: Was the index of the BEAN token in the BEAN:ETH Uniswap V2 pool.\n * @param deprecated_cases DEPRECATED: The 24 Weather cases used in cases V1 (array has 32 items, but caseId = 3 (mod 4) are not cases)\n * @param paused True if Beanstalk is Paused.\n * @param pausedAt The timestamp at which Beanstalk was last paused.\n * @param season Storage.Season\n * @param c Storage.Contracts\n * @param f Storage.Field\n * @param g Storage.Governance\n * @param co Storage.CurveMetapoolOracle\n * @param r Storage.Rain\n * @param s Storage.Silo\n * @param reentrantStatus An intra-transaction state variable to protect against reentrance.\n * @param w Storage.Weather\n * @param earnedBeans The number of Beans distributed to the Silo that have not yet been Deposited as a result of the Earn function being called.\n * @param deprecated DEPRECATED - 14 slots that used to store state variables which have been deprecated through various updates. Storage slots can be left alone or reused.\n * @param a mapping (address => Account.State)\n * @param deprecated_bip0Start DEPRECATED - bip0Start was used to aid in a migration that occured alongside BIP-0.\n * @param deprecated_hotFix3Start DEPRECATED - hotFix3Start was used to aid in a migration that occured alongside HOTFIX-3.\n * @param fundraisers A mapping from Fundraiser ID to Storage.Fundraiser.\n * @param fundraiserIndex The number of Fundraisers that have occured.\n * @param deprecated_isBudget DEPRECATED - Budget Facet was removed in BIP-14. \n * @param podListings A mapping from Plot Index to the hash of the Pod Listing.\n * @param podOrders A mapping from the hash of a Pod Order to the amount of Pods that the Pod Order is still willing to buy.\n * @param siloBalances A mapping from Token address to Silo Balance storage (amount deposited and withdrawn).\n * @param ss A mapping from Token address to Silo Settings for each Whitelisted Token. If a non-zero storage exists, a Token is whitelisted.\n * @param deprecated2 DEPRECATED - 2 slots that used to store state variables which have been deprecated through various updates. Storage slots can be left alone or reused.\n * @param deprecated_newEarnedStalk the amount of earned stalk issued this season. Since 1 stalk = 1 bean, it represents the earned beans as well.\n * @param sops A mapping from Season to Plenty Per Root (PPR) in that Season. Plenty Per Root is 0 if a Season of Plenty did not occur.\n * @param internalTokenBalance A mapping from Farmer address to Token address to Internal Balance. It stores the amount of the Token that the Farmer has stored as an Internal Balance in Beanstalk.\n * @param unripeClaimed True if a Farmer has Claimed an Unripe Token. A mapping from Farmer to Unripe Token to its Claim status.\n * @param u Unripe Settings for a given Token address. The existence of a non-zero Unripe Settings implies that the token is an Unripe Token. The mapping is from Token address to Unripe Settings.\n * @param fertilizer A mapping from Fertilizer Id to the supply of Fertilizer for each Id.\n * @param nextFid A linked list of Fertilizer Ids ordered by Id number. Fertilizer Id is the Beans Per Fertilzer level at which the Fertilizer no longer receives Beans. Sort in order by which Fertilizer Id expires next.\n * @param activeFertilizer The number of active Fertilizer.\n * @param fertilizedIndex The total number of Fertilizer Beans.\n * @param unfertilizedIndex The total number of Unfertilized Beans ever.\n * @param fFirst The lowest active Fertilizer Id (start of linked list that is stored by nextFid). \n * @param fLast The highest active Fertilizer Id (end of linked list that is stored by nextFid). \n * @param bpf The cumulative Beans Per Fertilizer (bfp) minted over all Season.\n * @param deprecated_vestingPeriodRoots deprecated - removed in BIP-39 in favor of germination.\n * @param recapitalized The number of USDC that has been recapitalized in the Barn Raise.\n * @param isFarm Stores whether the function is wrapped in the `farm` function (1 if not, 2 if it is).\n * @param ownerCandidate Stores a candidate address to transfer ownership to. The owner must claim the ownership transfer.\n * @param wellOracleSnapshots A mapping from Well Oracle address to the Well Oracle Snapshot.\n * @param deprecated_beanEthPrice DEPRECATED - The price of bean:eth, originally used to calculate the incentive reward. Deprecated in favor of calculating using twaReserves.\n * @param twaReserves A mapping from well to its twaReserves. Stores twaReserves during the sunrise function. Returns 1 otherwise for each asset. Currently supports 2 token wells.\n * @param migratedBdvs Stores the total migrated BDV since the implementation of the migrated BDV counter. See {LibLegacyTokenSilo.incrementMigratedBdv} for more info.\n * @param usdEthPrice  Stores the usdEthPrice during the sunrise() function. Returns 1 otherwise.\n * @param seedGauge Stores the seedGauge.\n * @param casesV2 Stores the 144 Weather and seedGauge cases.\n * @param oddGerminating Stores germinating data during odd seasons.\n * @param evenGerminating Stores germinating data during even seasons.\n * @param whitelistedStatues Stores a list of Whitelist Statues for all tokens that have been Whitelisted and have not had their Whitelist Status manually removed.\n * @param sopWell Stores the well that will be used upon a SOP. Unintialized until a SOP occurs, and is kept constant afterwards.\n */\nstruct AppStorage {\n    uint8 deprecated_index;\n    int8[32] deprecated_cases; \n    bool paused; // ────────┐ 1 \n    uint128 pausedAt; // ───┘ 16 (17/32)\n    Storage.Season season;\n    Storage.Contracts c;\n    Storage.Field f;\n    Storage.Governance g;\n    Storage.CurveMetapoolOracle co;\n    Storage.Rain r;\n    Storage.Silo s;\n    uint256 reentrantStatus;\n    Storage.Weather w;\n\n    uint256 earnedBeans;\n    uint256[14] deprecated;\n    mapping (address => Account.State) a;\n    uint32 deprecated_bip0Start; // ─────┐ 4\n    uint32 deprecated_hotFix3Start; // ──┘ 4 (8/32)\n    mapping (uint32 => Storage.Fundraiser) fundraisers;\n    uint32 fundraiserIndex; // 4 (4/32)\n    mapping (address => bool) deprecated_isBudget;\n    mapping(uint256 => bytes32) podListings;\n    mapping(bytes32 => uint256) podOrders;\n    mapping(address => Storage.AssetSilo) siloBalances;\n    mapping(address => Storage.SiloSettings) ss;\n    uint256[2] deprecated2;\n    uint128 deprecated_newEarnedStalk; // ──────┐ 16\n    uint128 deprecated_vestingPeriodRoots; // ──┘ 16 (32/32)\n    mapping (uint32 => uint256) sops;\n\n    // Internal Balances\n    mapping(address => mapping(IERC20 => uint256)) internalTokenBalance;\n\n    // Unripe\n    mapping(address => mapping(address => bool)) unripeClaimed;\n    mapping(address => Storage.UnripeSettings) u;\n\n    // Fertilizer\n    mapping(uint128 => uint256) fertilizer;\n    mapping(uint128 => uint128) nextFid;\n    uint256 activeFertilizer;\n    uint256 fertilizedIndex;\n    uint256 unfertilizedIndex;\n    uint128 fFirst;\n    uint128 fLast;\n    uint128 bpf;\n    uint256 recapitalized;\n\n    // Farm\n    uint256 isFarm;\n\n    // Ownership\n    address ownerCandidate;\n\n    // Well\n    mapping(address => bytes) wellOracleSnapshots;\n\n    uint256 deprecated_beanEthPrice;\n\n    // Silo V3 BDV Migration\n    mapping(address => uint256) migratedBdvs;\n\n    // Well/Curve + USD Price Oracle\n    mapping(address => Storage.TwaReserves) twaReserves;\n    mapping(address => uint256) usdTokenPrice;\n\n    // Seed Gauge\n    Storage.SeedGauge seedGauge;\n    bytes32[144] casesV2;\n\n    // Germination\n    Storage.TotalGerminating oddGerminating;\n    Storage.TotalGerminating evenGerminating;\n\n    // mapping from season => unclaimed germinating stalk and roots \n    mapping(uint32 => Storage.Sr) unclaimedGerminating;\n\n    Storage.WhitelistStatus[] whitelistStatuses;\n\n    address sopWell;\n}"
      },
      "contracts/beanstalk/silo/BDVFacet.sol": {
        "content": "/*\n * SPDX-License-Identifier: MIT\n */\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport \"contracts/C.sol\";\nimport \"contracts/libraries/Curve/LibBeanMetaCurve.sol\";\nimport \"contracts/libraries/LibUnripe.sol\";\nimport \"contracts/libraries/Well/LibWellBdv.sol\";\n\n/**\n * @title BDVFacet\n * @author Publius\n * @notice Calculates BDV for whitelisted Silo tokens.\n */\ncontract BDVFacet {\n    using SafeMath for uint256;\n\n    /**\n     * @dev Returns the BDV of a given `amount` of Bean:3Crv LP tokens.\n     */\n    function curveToBDV(uint256 amount) public view returns (uint256) {\n        return LibBeanMetaCurve.bdv(amount);\n    }\n    /**\n     * @dev Returns the BDV of a given `amount` of Beans.\n     */\n    function beanToBDV(uint256 amount) public pure returns (uint256) {\n        return amount;\n    }\n\n    /**\n     * @dev Returns the BDV of a given `amount` of Unripe Bean:3Crv LP Tokens.\n     */\n    function unripeLPToBDV(uint256 amount) public view returns (uint256) {\n        amount = LibUnripe.unripeToUnderlying(\n            C.UNRIPE_LP, \n            amount, \n            IBean(C.UNRIPE_LP).totalSupply()\n        );\n        amount = LibWellBdv.bdv(C.BEAN_ETH_WELL, amount);\n        return amount;\n    }\n\n    /**\n     * @dev Returns the BDV of a given `amount` of Unripe Beans.\n     */\n    function unripeBeanToBDV(uint256 amount) public view returns (uint256) {\n        return LibUnripe.unripeToUnderlying(\n            C.UNRIPE_BEAN, \n            amount, \n            IBean(C.UNRIPE_BEAN).totalSupply()\n        );\n    }\n\n    /**\n     * @dev Returns the BDV of a given `amount` of Well LP Tokens given a Well `token`.\n     * A Well's `token` address is the same as the Well address.\n     * Any Well `token` that uses the `wellBdv` function as its BDV function must have \n     `encodeType = 1` in {Storage.SiloSettings}.\n     */\n    function wellBdv(address token, uint256 amount)\n        external\n        view\n        returns (uint256)\n    {\n        return LibWellBdv.bdv(token, amount);\n    }\n}\n"
      },
      "contracts/C.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport \"./interfaces/IBean.sol\";\nimport \"./interfaces/ICurve.sol\";\nimport \"./interfaces/IFertilizer.sol\";\nimport \"./interfaces/IProxyAdmin.sol\";\nimport \"./libraries/Decimal.sol\";\n\n/**\n * @title C\n * @author Publius\n * @notice Contains constants used throughout Beanstalk.\n */\nlibrary C {\n    using Decimal for Decimal.D256;\n    using SafeMath for uint256;\n\n    //////////////////// Globals ////////////////////\n\n    uint256 internal constant PRECISION = 1e18;\n    uint256 private constant CHAIN_ID = 1;\n    bytes constant BYTES_ZERO = new bytes(0);\n\n    /// @dev The block time for the chain in seconds.\n    uint256 internal constant BLOCK_LENGTH_SECONDS = 12;\n\n    //////////////////// Season ////////////////////\n\n    /// @dev The length of a Season meaured in seconds.\n    uint256 private constant CURRENT_SEASON_PERIOD = 3600; // 1 hour\n    uint256 internal constant SOP_PRECISION = 1e24;\n\n    //////////////////// Silo ////////////////////\n\n    uint256 internal constant SEEDS_PER_BEAN = 2;\n    uint256 internal constant STALK_PER_BEAN = 10000;\n    uint256 private constant ROOTS_BASE = 1e12;\n\n    //////////////////// Exploit Migration ////////////////////\n\n    uint256 private constant UNRIPE_LP_PER_DOLLAR = 1884592; // 145_113_507_403_282 / 77_000_000\n    uint256 private constant ADD_LP_RATIO = 866616;\n    uint256 private constant INITIAL_HAIRCUT = 185564685220298701;\n\n    //////////////////// Contracts ////////////////////\n\n    address internal constant BEAN = 0xBEA0000029AD1c77D3d5D23Ba2D8893dB9d1Efab;\n    address internal constant CURVE_BEAN_METAPOOL = 0xc9C32cd16Bf7eFB85Ff14e0c8603cc90F6F2eE49;\n\n    address internal constant UNRIPE_BEAN = 0x1BEA0050E63e05FBb5D8BA2f10cf5800B6224449;\n    address internal constant UNRIPE_LP = 0x1BEA3CcD22F4EBd3d37d731BA31Eeca95713716D;\n\n    address private constant CURVE_3_POOL = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;\n    address private constant THREE_CRV = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;\n\n    address private constant FERTILIZER = 0x402c84De2Ce49aF88f5e2eF3710ff89bFED36cB6;\n    address private constant FERTILIZER_ADMIN = 0xfECB01359263C12Aa9eD838F878A596F0064aa6e;\n\n    address private constant TRI_CRYPTO = 0xc4AD29ba4B3c580e6D59105FFf484999997675Ff;\n    address private constant TRI_CRYPTO_POOL = 0xD51a44d3FaE010294C616388b506AcdA1bfAAE46;\n    address private constant CURVE_ZAP = 0xA79828DF1850E8a3A3064576f380D90aECDD3359;\n\n    address private constant UNRIPE_CURVE_BEAN_LUSD_POOL = 0xD652c40fBb3f06d6B58Cb9aa9CFF063eE63d465D;\n    address private constant UNRIPE_CURVE_BEAN_METAPOOL = 0x3a70DfA7d2262988064A2D051dd47521E43c9BdD;\n\n    address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;\n    address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;\n    address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;\n    address internal constant UNIV3_ETH_USDC_POOL = 0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640; // 0.05% pool\n    address internal constant UNIV3_ETH_USDT_POOL = 0x11b815efB8f581194ae79006d24E0d814B7697F6; // 0.05% pool\n\n    // Use external contract for block.basefee as to avoid upgrading existing contracts to solidity v8\n    address private constant BASE_FEE_CONTRACT = 0x84292919cB64b590C0131550483707E43Ef223aC;\n\n    //////////////////// Well ////////////////////\n\n    uint256 internal constant WELL_MINIMUM_BEAN_BALANCE = 1000_000_000; // 1,000 Beans\n    address internal constant BEANSTALK_PUMP = 0xBA510f10E3095B83a0F33aa9ad2544E22570a87C;\n    address internal constant BEAN_ETH_WELL = 0xBEA0e11282e2bB5893bEcE110cF199501e872bAd;\n    // The index of the Bean and Weth token addresses in all BEAN/ETH Wells.\n    uint256 internal constant BEAN_INDEX = 0;\n    uint256 internal constant ETH_INDEX = 1;\n\n    function getSeasonPeriod() internal pure returns (uint256) {\n        return CURRENT_SEASON_PERIOD;\n    }\n\n    function getBlockLengthSeconds() internal pure returns (uint256) {\n        return BLOCK_LENGTH_SECONDS;\n    }\n\n    function getChainId() internal pure returns (uint256) {\n        return CHAIN_ID;\n    }\n\n    function getSeedsPerBean() internal pure returns (uint256) {\n        return SEEDS_PER_BEAN;\n    }\n\n    function getStalkPerBean() internal pure returns (uint256) {\n      return STALK_PER_BEAN;\n    }\n\n    function getRootsBase() internal pure returns (uint256) {\n        return ROOTS_BASE;\n    }\n\n    /**\n     * @dev The pre-exploit BEAN:3CRV Curve metapool address.\n     */\n    function unripeLPPool1() internal pure returns (address) {\n        return UNRIPE_CURVE_BEAN_METAPOOL;\n    }\n\n    /**\n     * @dev The pre-exploit BEAN:LUSD Curve plain pool address.\n     */\n    function unripeLPPool2() internal pure returns (address) {\n        return UNRIPE_CURVE_BEAN_LUSD_POOL;\n    }\n\n    function unripeBean() internal pure returns (IERC20) {\n        return IERC20(UNRIPE_BEAN);\n    }\n\n    function unripeLP() internal pure returns (IERC20) {\n        return IERC20(UNRIPE_LP);\n    }\n\n    function bean() internal pure returns (IBean) {\n        return IBean(BEAN);\n    }\n\n    function usdc() internal pure returns (IERC20) {\n        return IERC20(USDC);\n    }\n\n    function curveMetapool() internal pure returns (ICurvePool) {\n        return ICurvePool(CURVE_BEAN_METAPOOL);\n    }\n\n    function curve3Pool() internal pure returns (I3Curve) {\n        return I3Curve(CURVE_3_POOL);\n    }\n    \n    function curveZap() internal pure returns (ICurveZap) {\n        return ICurveZap(CURVE_ZAP);\n    }\n\n    function curveZapAddress() internal pure returns (address) {\n        return CURVE_ZAP;\n    }\n\n    function curve3PoolAddress() internal pure returns (address) {\n        return CURVE_3_POOL;\n    }\n\n    function threeCrv() internal pure returns (IERC20) {\n        return IERC20(THREE_CRV);\n    }\n\n    function UniV3EthUsdc() internal pure returns (address){\n        return UNIV3_ETH_USDC_POOL;\n    }\n\n    function fertilizer() internal pure returns (IFertilizer) {\n        return IFertilizer(FERTILIZER);\n    }\n\n    function fertilizerAddress() internal pure returns (address) {\n        return FERTILIZER;\n    }\n\n    function fertilizerAdmin() internal pure returns (IProxyAdmin) {\n        return IProxyAdmin(FERTILIZER_ADMIN);\n    }\n\n    function triCryptoPoolAddress() internal pure returns (address) {\n        return TRI_CRYPTO_POOL;\n    }\n\n    function triCrypto() internal pure returns (IERC20) {\n        return IERC20(TRI_CRYPTO);\n    }\n\n    function unripeLPPerDollar() internal pure returns (uint256) {\n        return UNRIPE_LP_PER_DOLLAR;\n    }\n\n    function dollarPerUnripeLP() internal pure returns (uint256) {\n        return 1e12/UNRIPE_LP_PER_DOLLAR;\n    }\n\n    function exploitAddLPRatio() internal pure returns (uint256) {\n        return ADD_LP_RATIO;\n    }\n\n    function precision() internal pure returns (uint256) {\n        return PRECISION;\n    }\n\n    function initialRecap() internal pure returns (uint256) {\n        return INITIAL_HAIRCUT;\n    }\n\n}"
      },
      "contracts/interfaces/basin/IWell.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/**\n * @title Call is the struct that contains the target address and extra calldata of a generic call.\n */\nstruct Call {\n    address target; // The address the call is executed on.\n    bytes data; // Extra calldata to be passed during the call\n}\n\n/**\n * @title IWell is the interface for the Well contract.\n *\n * In order for a Well to be verified using a permissionless on-chain registry, a Well Implementation should:\n * - Not be able to self-destruct (Aquifer's registry would be vulnerable to a metamorphic contract attack)\n * - Not be able to change its tokens, Well Function, Pumps and Well Data\n */\ninterface IWell {\n    /**\n     * @notice Emitted when a Swap occurs.\n     * @param fromToken The token swapped from\n     * @param toToken The token swapped to\n     * @param amountIn The amount of `fromToken` transferred into the Well\n     * @param amountOut The amount of `toToken` transferred out of the Well\n     * @param recipient The address that received `toToken`\n     */\n    event Swap(IERC20 fromToken, IERC20 toToken, uint256 amountIn, uint256 amountOut, address recipient);\n\n    /**\n     * @notice Emitted when liquidity is added to the Well.\n     * @param tokenAmountsIn The amount of each token added to the Well\n     * @param lpAmountOut The amount of LP tokens minted\n     * @param recipient The address that received the LP tokens\n     */\n    event AddLiquidity(uint256[] tokenAmountsIn, uint256 lpAmountOut, address recipient);\n\n    /**\n     * @notice Emitted when liquidity is removed from the Well as multiple underlying tokens.\n     * @param lpAmountIn The amount of LP tokens burned\n     * @param tokenAmountsOut The amount of each underlying token removed\n     * @param recipient The address that received the underlying tokens\n     * @dev Gas cost scales with `n` tokens.\n     */\n    event RemoveLiquidity(uint256 lpAmountIn, uint256[] tokenAmountsOut, address recipient);\n\n    /**\n     * @notice Emitted when liquidity is removed from the Well as a single underlying token.\n     * @param lpAmountIn The amount of LP tokens burned\n     * @param tokenOut The underlying token removed\n     * @param tokenAmountOut The amount of `tokenOut` removed\n     * @param recipient The address that received the underlying tokens\n     * @dev Emitting a separate event when removing liquidity as a single token\n     * saves gas, since `tokenAmountsOut` in {RemoveLiquidity} must emit a value\n     * for each token in the Well.\n     */\n    event RemoveLiquidityOneToken(uint256 lpAmountIn, IERC20 tokenOut, uint256 tokenAmountOut, address recipient);\n\n    /**\n     * @notice Emitted when a Shift occurs.\n     * @param reserves The ending reserves after a shift\n     * @param toToken The token swapped to\n     * @param amountOut The amount of `toToken` transferred out of the Well\n     * @param recipient The address that received `toToken`\n     */\n    event Shift(uint256[] reserves, IERC20 toToken, uint256 amountOut, address recipient);\n\n    /**\n     * @notice Emitted when a Sync occurs.\n     * @param reserves The ending reserves after a sync\n     * @param lpAmountOut The amount of LP tokens received from the sync.\n     * @param recipient The address that received the LP tokens\n     */\n    event Sync(uint256[] reserves, uint256 lpAmountOut, address recipient);\n\n    //////////////////// WELL DEFINITION ////////////////////\n\n    /**\n     * @notice Returns a list of ERC20 tokens supported by the Well.\n     */\n    function tokens() external view returns (IERC20[] memory);\n\n    /**\n     * @notice Returns the Well function as a Call struct.\n     * @dev Contains the address of the Well function contract and extra data to\n     * pass during calls.\n     *\n     * **Well functions** define a relationship between the reserves of the\n     * tokens in the Well and the number of LP tokens.\n     *\n     * A Well function MUST implement {IWellFunction}.\n     */\n    function wellFunction() external view returns (Call memory);\n\n    /**\n     * @notice Returns the Pumps attached to the Well as Call structs.\n     * @dev Contains the addresses of the Pumps contract and extra data to pass\n     * during calls.\n     *\n     * **Pumps** are on-chain oracles that are updated every time the Well is\n     * interacted with.\n     *\n     * A Pump is not required for Well operation. For Wells without a Pump:\n     * `pumps().length = 0`.\n     *\n     * An attached Pump MUST implement {IPump}.\n     */\n    function pumps() external view returns (Call[] memory);\n\n    /**\n     * @notice Returns the Well data that the Well was bored with.\n     * @dev The existence and signature of Well data is determined by each individual implementation.\n     */\n    function wellData() external view returns (bytes memory);\n\n    /**\n     * @notice Returns the Aquifer that created this Well.\n     * @dev Wells can be permissionlessly bored in an Aquifer.\n     *\n     * Aquifers stores the implementation that was used to bore the Well.\n     */\n    function aquifer() external view returns (address);\n\n    /**\n     * @notice Returns the tokens, Well Function, Pumps and Well Data associated\n     * with the Well as well as the Aquifer that deployed the Well.\n     */\n    function well()\n        external\n        view\n        returns (\n            IERC20[] memory _tokens,\n            Call memory _wellFunction,\n            Call[] memory _pumps,\n            bytes memory _wellData,\n            address _aquifer\n        );\n\n    //////////////////// SWAP: FROM ////////////////////\n\n    /**\n     * @notice Swaps from an exact amount of `fromToken` to a minimum amount of `toToken`.\n     * @param fromToken The token to swap from\n     * @param toToken The token to swap to\n     * @param amountIn The amount of `fromToken` to spend\n     * @param minAmountOut The minimum amount of `toToken` to receive\n     * @param recipient The address to receive `toToken`\n     * @param deadline The timestamp after which this operation is invalid\n     * @return amountOut The amount of `toToken` received\n     */\n    function swapFrom(\n        IERC20 fromToken,\n        IERC20 toToken,\n        uint256 amountIn,\n        uint256 minAmountOut,\n        address recipient,\n        uint256 deadline\n    ) external returns (uint256 amountOut);\n\n    /**\n     * @notice Swaps from an exact amount of `fromToken` to a minimum amount of `toToken` and supports fee on transfer tokens.\n     * @param fromToken The token to swap from\n     * @param toToken The token to swap to\n     * @param amountIn The amount of `fromToken` to spend\n     * @param minAmountOut The minimum amount of `toToken` to take from the Well. Note that if `toToken` charges a fee on transfer, `recipient` will receive less than this amount.\n     * @param recipient The address to receive `toToken`\n     * @param deadline The timestamp after which this operation is invalid\n     * @return amountOut The amount of `toToken` transferred from the Well. Note that if `toToken` charges a fee on transfer, `recipient` may receive less than this amount.\n     * @dev Can also be used for tokens without a fee on transfer, but is less gas efficient.\n     */\n    function swapFromFeeOnTransfer(\n        IERC20 fromToken,\n        IERC20 toToken,\n        uint256 amountIn,\n        uint256 minAmountOut,\n        address recipient,\n        uint256 deadline\n    ) external returns (uint256 amountOut);\n\n    /**\n     * @notice Gets the amount of one token received for swapping an amount of another token.\n     * @param fromToken The token to swap from\n     * @param toToken The token to swap to\n     * @param amountIn The amount of `fromToken` to spend\n     * @return amountOut The amount of `toToken` to receive\n     */\n    function getSwapOut(IERC20 fromToken, IERC20 toToken, uint256 amountIn) external view returns (uint256 amountOut);\n\n    //////////////////// SWAP: TO ////////////////////\n\n    /**\n     * @notice Swaps from a maximum amount of `fromToken` to an exact amount of `toToken`.\n     * @param fromToken The token to swap from\n     * @param toToken The token to swap to\n     * @param maxAmountIn The maximum amount of `fromToken` to spend\n     * @param amountOut The amount of `toToken` to receive\n     * @param recipient The address to receive `toToken`\n     * @param deadline The timestamp after which this operation is invalid\n     * @return amountIn The amount of `toToken` received\n     */\n    function swapTo(\n        IERC20 fromToken,\n        IERC20 toToken,\n        uint256 maxAmountIn,\n        uint256 amountOut,\n        address recipient,\n        uint256 deadline\n    ) external returns (uint256 amountIn);\n\n    /**\n     * @notice Gets the amount of one token that must be spent to receive an amount of another token during a swap.\n     * @param fromToken The token to swap from\n     * @param toToken The token to swap to\n     * @param amountOut The amount of `toToken` desired\n     * @return amountIn The amount of `fromToken` that must be spent\n     */\n    function getSwapIn(IERC20 fromToken, IERC20 toToken, uint256 amountOut) external view returns (uint256 amountIn);\n\n    //////////////////// SHIFT ////////////////////\n\n    /**\n     * @notice Shifts at least `minAmountOut` excess tokens held by the Well into `tokenOut` and delivers to `recipient`.\n     * @param tokenOut The token to shift into\n     * @param minAmountOut The minimum amount of `tokenOut` to receive\n     * @param recipient The address to receive the token\n     * @return amountOut The amount of `tokenOut` received\n     * @dev Can be used in a multicall using a contract like Pipeline to perform gas efficient swaps.\n     * No deadline is needed since this function does not use the user's assets. If adding liquidity in a multicall,\n     * then a deadline check can be added to the multicall.\n     */\n    function shift(IERC20 tokenOut, uint256 minAmountOut, address recipient) external returns (uint256 amountOut);\n\n    /**\n     * @notice Calculates the amount of the token out received from shifting excess tokens held by the Well.\n     * @param tokenOut The token to shift into\n     * @return amountOut The amount of `tokenOut` received\n     */\n    function getShiftOut(IERC20 tokenOut) external returns (uint256 amountOut);\n\n    //////////////////// ADD LIQUIDITY ////////////////////\n\n    /**\n     * @notice Adds liquidity to the Well as multiple tokens in any ratio.\n     * @param tokenAmountsIn The amount of each token to add; MUST match the indexing of {Well.tokens}\n     * @param minLpAmountOut The minimum amount of LP tokens to receive\n     * @param recipient The address to receive the LP tokens\n     * @param deadline The timestamp after which this operation is invalid\n     * @return lpAmountOut The amount of LP tokens received\n     */\n    function addLiquidity(\n        uint256[] memory tokenAmountsIn,\n        uint256 minLpAmountOut,\n        address recipient,\n        uint256 deadline\n    ) external returns (uint256 lpAmountOut);\n\n    /**\n     * @notice Adds liquidity to the Well as multiple tokens in any ratio and supports\n     * fee on transfer tokens.\n     * @param tokenAmountsIn The amount of each token to add; MUST match the indexing of {Well.tokens}\n     * @param minLpAmountOut The minimum amount of LP tokens to receive\n     * @param recipient The address to receive the LP tokens\n     * @param deadline The timestamp after which this operation is invalid\n     * @return lpAmountOut The amount of LP tokens received\n     * @dev Can also be used for tokens without a fee on transfer, but is less gas efficient.\n     */\n    function addLiquidityFeeOnTransfer(\n        uint256[] memory tokenAmountsIn,\n        uint256 minLpAmountOut,\n        address recipient,\n        uint256 deadline\n    ) external returns (uint256 lpAmountOut);\n\n    /**\n     * @notice Gets the amount of LP tokens received from adding liquidity as multiple tokens in any ratio.\n     * @param tokenAmountsIn The amount of each token to add; MUST match the indexing of {Well.tokens}\n     * @return lpAmountOut The amount of LP tokens received\n     */\n    function getAddLiquidityOut(uint256[] memory tokenAmountsIn) external view returns (uint256 lpAmountOut);\n\n    //////////////////// REMOVE LIQUIDITY: BALANCED ////////////////////\n\n    /**\n     * @notice Removes liquidity from the Well as all underlying tokens in a balanced ratio.\n     * @param lpAmountIn The amount of LP tokens to burn\n     * @param minTokenAmountsOut The minimum amount of each underlying token to receive; MUST match the indexing of {Well.tokens}\n     * @param recipient The address to receive the underlying tokens\n     * @param deadline The timestamp after which this operation is invalid\n     * @return tokenAmountsOut The amount of each underlying token received\n     */\n    function removeLiquidity(\n        uint256 lpAmountIn,\n        uint256[] calldata minTokenAmountsOut,\n        address recipient,\n        uint256 deadline\n    ) external returns (uint256[] memory tokenAmountsOut);\n\n    /**\n     * @notice Gets the amount of each underlying token received from removing liquidity in a balanced ratio.\n     * @param lpAmountIn The amount of LP tokens to burn\n     * @return tokenAmountsOut The amount of each underlying token received\n     */\n    function getRemoveLiquidityOut(uint256 lpAmountIn) external view returns (uint256[] memory tokenAmountsOut);\n\n    //////////////////// REMOVE LIQUIDITY: ONE TOKEN ////////////////////\n\n    /**\n     * @notice Removes liquidity from the Well as a single underlying token.\n     * @param lpAmountIn The amount of LP tokens to burn\n     * @param tokenOut The underlying token to receive\n     * @param minTokenAmountOut The minimum amount of `tokenOut` to receive\n     * @param recipient The address to receive the underlying tokens\n     * @param deadline The timestamp after which this operation is invalid\n     * @return tokenAmountOut The amount of `tokenOut` received\n     */\n    function removeLiquidityOneToken(\n        uint256 lpAmountIn,\n        IERC20 tokenOut,\n        uint256 minTokenAmountOut,\n        address recipient,\n        uint256 deadline\n    ) external returns (uint256 tokenAmountOut);\n\n    /**\n     * @notice Gets the amount received from removing liquidity from the Well as a single underlying token.\n     * @param lpAmountIn The amount of LP tokens to burn\n     * @param tokenOut The underlying token to receive\n     * @return tokenAmountOut The amount of `tokenOut` received\n     *\n     */\n    function getRemoveLiquidityOneTokenOut(\n        uint256 lpAmountIn,\n        IERC20 tokenOut\n    ) external view returns (uint256 tokenAmountOut);\n\n    //////////////////// REMOVE LIQUIDITY: IMBALANCED ////////////////////\n\n    /**\n     * @notice Removes liquidity from the Well as multiple underlying tokens in any ratio.\n     * @param maxLpAmountIn The maximum amount of LP tokens to burn\n     * @param tokenAmountsOut The amount of each underlying token to receive; MUST match the indexing of {Well.tokens}\n     * @param recipient The address to receive the underlying tokens\n     * @return lpAmountIn The amount of LP tokens burned\n     */\n    function removeLiquidityImbalanced(\n        uint256 maxLpAmountIn,\n        uint256[] calldata tokenAmountsOut,\n        address recipient,\n        uint256 deadline\n    ) external returns (uint256 lpAmountIn);\n\n    /**\n     * @notice Gets the amount of LP tokens to burn from removing liquidity as multiple underlying tokens in any ratio.\n     * @param tokenAmountsOut The amount of each underlying token to receive; MUST match the indexing of {Well.tokens}\n     * @return lpAmountIn The amount of LP tokens burned\n     */\n    function getRemoveLiquidityImbalancedIn(uint256[] calldata tokenAmountsOut)\n        external\n        view\n        returns (uint256 lpAmountIn);\n\n    //////////////////// RESERVES ////////////////////\n\n    /**\n     * @notice Syncs the Well's reserves with the Well's balances of underlying tokens. If the reserves\n     * increase, mints at least `minLpAmountOut` LP Tokens to `recipient`.\n     * @param recipient The address to receive the LP tokens\n     * @param minLpAmountOut The minimum amount of LP tokens to receive\n     * @return lpAmountOut The amount of LP tokens received\n     * @dev Can be used in a multicall using a contract like Pipeline to perform gas efficient additions of liquidity.\n     * No deadline is needed since this function does not use the user's assets. If adding liquidity in a multicall,\n     * then a deadline check can be added to the multicall.\n     * If `sync` decreases the Well's reserves, then no LP tokens are minted and `lpAmountOut` must be 0.\n     */\n    function sync(address recipient, uint256 minLpAmountOut) external returns (uint256 lpAmountOut);\n\n    /**\n     * @notice Calculates the amount of LP Tokens received from syncing the Well's reserves with the Well's balances.\n     * @return lpAmountOut The amount of LP tokens received\n     */\n    function getSyncOut() external view returns (uint256 lpAmountOut);\n\n    /**\n     * @notice Sends excess tokens held by the Well to the `recipient`.\n     * @param recipient The address to send the tokens\n     * @return skimAmounts The amount of each token skimmed\n     * @dev No deadline is needed since this function does not use the user's assets.\n     */\n    function skim(address recipient) external returns (uint256[] memory skimAmounts);\n\n    /**\n     * @notice Gets the reserves of each token held by the Well.\n     */\n    function getReserves() external view returns (uint256[] memory reserves);\n\n    /**\n     * @notice Returns whether or not the Well is initialized if it requires initialization.\n     * If a Well does not require initialization, it should always return `true`.\n     */\n    function isInitialized() external view returns (bool);\n}"
      },
      "contracts/interfaces/basin/IWellFunction.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\n/**\n * @title IWellFunction\n * @notice Defines a relationship between token reserves and LP token supply.\n * @dev Well Functions can contain arbitrary logic, but should be deterministic\n * if expected to be used alongside a Pump. When interacing with a Well or\n * Well Function, always verify that the Well Function is valid.\n */\ninterface IWellFunction {\n    /**\n     * @notice Calculates the `j`th reserve given a list of `reserves` and `lpTokenSupply`.\n     * @param reserves A list of token reserves. The jth reserve will be ignored, but a placeholder must be provided.\n     * @param j The index of the reserve to solve for\n     * @param lpTokenSupply The supply of LP tokens\n     * @param data Extra Well function data provided on every call\n     * @return reserve The resulting reserve at the jth index\n     * @dev Should round up to ensure that Well reserves are marginally higher to enforce calcLpTokenSupply(...) >= totalSupply()\n     */\n    function calcReserve(\n        uint[] memory reserves,\n        uint j,\n        uint lpTokenSupply,\n        bytes calldata data\n    ) external view returns (uint reserve);\n\n    /**\n     * @notice Gets the LP token supply given a list of reserves.\n     * @param reserves A list of token reserves\n     * @param data Extra Well function data provided on every call\n     * @return lpTokenSupply The resulting supply of LP tokens\n     * @dev Should round down to ensure so that the Well Token supply is marignally lower to enforce calcLpTokenSupply(...) >= totalSupply()\n     */\n    function calcLpTokenSupply(\n        uint[] memory reserves,\n        bytes calldata data\n    ) external view returns (uint lpTokenSupply);\n\n    /**\n     * @notice Calculates the amount of each reserve token underlying a given amount of LP tokens.\n     * @param lpTokenAmount An amount of LP tokens\n     * @param reserves A list of token reserves\n     * @param lpTokenSupply The current supply of LP tokens\n     * @param data Extra Well function data provided on every call\n     * @return underlyingAmounts The amount of each reserve token that underlies the LP tokens\n     * @dev The constraint totalSupply() <= calcLPTokenSupply(...) must be held in the case where\n     * `lpTokenAmount` LP tokens are burned in exchanged for `underlyingAmounts`. If the constraint\n     * does not hold, then the Well Function is invalid.\n     */\n    function calcLPTokenUnderlying(\n        uint lpTokenAmount,\n        uint[] memory reserves,\n        uint lpTokenSupply,\n        bytes calldata data\n    ) external view returns (uint[] memory underlyingAmounts);\n\n    /**\n     * @notice Returns the name of the Well function.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @notice Returns the symbol of the Well function.\n     */\n    function symbol() external view returns (string memory);\n}\n"
      },
      "contracts/interfaces/basin/pumps/ICumulativePump.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\n/**\n * @title ICumulativePump\n * @notice Provides an interface for Pumps which calculate time-weighted average\n * reserves through the use of a cumulative reserve.\n */\ninterface ICumulativePump {\n    /**\n     * @notice Reads the current cumulative reserves from the Pump\n     * @param well The address of the Well\n     * @param data data specific to the Well\n     * @return cumulativeReserves The cumulative reserves from the Pump\n     */\n    function readCumulativeReserves(\n        address well,\n        bytes memory data\n    ) external view returns (bytes memory cumulativeReserves);\n\n    /**\n     * @notice Reads the current cumulative reserves from the Pump\n     * @param well The address of the Well\n     * @param startCumulativeReserves The cumulative reserves to start the TWA from\n     * @param startTimestamp The timestamp to start the TWA from\n     * @param data data specific to the Well\n     * @return twaReserves The time weighted average reserves from start timestamp to now\n     * @return cumulativeReserves The current cumulative reserves from the Pump at the current timestamp\n     */\n    function readTwaReserves(\n        address well,\n        bytes calldata startCumulativeReserves,\n        uint startTimestamp,\n        bytes memory data\n    ) external view returns (uint[] memory twaReserves, bytes memory cumulativeReserves);\n}\n"
      },
      "contracts/interfaces/basin/pumps/IInstantaneousPump.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\n/**\n * @title Instantaneous Pumps provide an Oracle for instantaneous reserves.\n */\ninterface IInstantaneousPump {\n    /**\n     * @notice Reads instantaneous reserves from the Pump\n     * @param well The address of the Well\n     * @return reserves The instantaneous balanecs tracked by the Pump\n     */\n    function readInstantaneousReserves(\n        address well,\n        bytes memory data\n    ) external view returns (uint[] memory reserves);\n}\n"
      },
      "contracts/interfaces/chainlink/IChainlinkAggregator.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity =0.7.6;\n\ninterface IChainlinkAggregator {\n  function decimals() external view returns (uint8);\n\n  function description() external view returns (string memory);\n\n  function version() external view returns (uint256);\n\n  // getRoundData and latestRoundData should both raise \"No data present\"\n  // if they do not have data to report, instead of returning unset values\n  // which could be misinterpreted as actual reported values.\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}"
      },
      "contracts/interfaces/IBean.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/**\n * @title IBean\n * @author Publius\n * @notice Bean Interface\n */\nabstract contract IBean is IERC20 {\n    function burn(uint256 amount) public virtual;\n    function burnFrom(address account, uint256 amount) public virtual;\n    function mint(address account, uint256 amount) public virtual;\n    function symbol() public view virtual returns (string memory);\n}\n"
      },
      "contracts/interfaces/ICurve.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma experimental ABIEncoderV2;\npragma solidity =0.7.6;\n\ninterface ICurvePool {\n    function A_precise() external view returns (uint256);\n    function get_balances() external view returns (uint256[2] memory);\n    function totalSupply() external view returns (uint256);\n    function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external returns (uint256);\n    function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount) external returns (uint256);\n    function balances(int128 i) external view returns (uint256);\n    function fee() external view returns (uint256);\n    function coins(uint256 i) external view returns (address);\n    function get_virtual_price() external view returns (uint256);\n    function calc_token_amount(uint256[2] calldata amounts, bool deposit) external view returns (uint256);\n    function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);\n    function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256);\n    function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256);\n    function transfer(address recipient, uint256 amount) external returns (bool);\n}\n\ninterface ICurveZap {\n    function add_liquidity(address _pool, uint256[4] memory _deposit_amounts, uint256 _min_mint_amount) external returns (uint256);\n    function calc_token_amount(address _pool, uint256[4] memory _amounts, bool _is_deposit) external returns (uint256);\n}\n\ninterface ICurvePoolR {\n    function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);\n    function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);\n    function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount, address receiver) external returns (uint256);\n}\n\ninterface ICurvePool2R {\n    function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount, address reciever) external returns (uint256);\n    function remove_liquidity(uint256 _burn_amount, uint256[2] memory _min_amounts, address reciever) external returns (uint256[2] calldata);\n    function remove_liquidity_imbalance(uint256[2] memory _amounts, uint256 _max_burn_amount, address reciever) external returns (uint256);\n}\n\ninterface ICurvePool3R {\n    function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount, address reciever) external returns (uint256);\n    function remove_liquidity(uint256 _burn_amount, uint256[3] memory _min_amounts, address reciever) external returns (uint256[3] calldata);\n    function remove_liquidity_imbalance(uint256[3] memory _amounts, uint256 _max_burn_amount, address reciever) external returns (uint256);\n}\n\ninterface ICurvePool4R {\n    function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount, address reciever) external returns (uint256);\n    function remove_liquidity(uint256 _burn_amount, uint256[4] memory _min_amounts, address reciever) external returns (uint256[4] calldata);\n    function remove_liquidity_imbalance(uint256[4] memory _amounts, uint256 _max_burn_amount, address reciever) external returns (uint256);\n}\n\ninterface I3Curve {\n    function get_virtual_price() external view returns (uint256);\n}\n\ninterface ICurveFactory {\n    function get_coins(address _pool) external view returns (address[4] calldata);\n    function get_underlying_coins(address _pool) external view returns (address[8] calldata);\n}\n\ninterface ICurveCryptoFactory {\n    function get_coins(address _pool) external view returns (address[8] calldata);\n}\n\ninterface ICurvePoolC {\n    function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external returns (uint256);\n}\n\ninterface ICurvePoolNoReturn {\n    function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external;\n    function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external;\n    function remove_liquidity(uint256 _burn_amount, uint256[3] memory _min_amounts) external;\n    function remove_liquidity_imbalance(uint256[3] memory _amounts, uint256 _max_burn_amount) external;\n    function remove_liquidity_one_coin(uint256 _token_amount, uint256 i, uint256 min_amount) external;\n}\n\ninterface ICurvePoolNoReturn128 {\n    function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external;\n    function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount) external;\n}\n"
      },
      "contracts/interfaces/IDiamondCut.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma experimental ABIEncoderV2;\npragma solidity =0.7.6;\n/******************************************************************************\\\n* Author: Nick Mudge <nick@perfectabstractions.com> (https://twitter.com/mudgen)\n/******************************************************************************/\n\ninterface IDiamondCut {\n    enum FacetCutAction {Add, Replace, Remove}\n\n    struct FacetCut {\n        address facetAddress;\n        FacetCutAction action;\n        bytes4[] functionSelectors;\n    }\n\n    /// @notice Add/replace/remove any number of functions and optionally execute\n    ///         a function with delegatecall\n    /// @param _diamondCut Contains the facet addresses and function selectors\n    /// @param _init The address of the contract or facet to execute _calldata\n    /// @param _calldata A function call, including function selector and arguments\n    ///                  _calldata is executed with delegatecall on _init\n    function diamondCut(\n        FacetCut[] calldata _diamondCut,\n        address _init,\n        bytes calldata _calldata\n    ) external;\n\n    event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);\n}\n"
      },
      "contracts/interfaces/IFertilizer.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma experimental ABIEncoderV2;\npragma solidity =0.7.6;\n\ninterface IFertilizer {\n    struct Balance {\n        uint128 amount;\n        uint128 lastBpf;\n    }\n    function beanstalkUpdate(\n        address account,\n        uint256[] memory ids,\n        uint128 bpf\n    ) external returns (uint256);\n    function beanstalkMint(address account, uint256 id, uint128 amount, uint128 bpf) external;\n    function balanceOfFertilized(address account, uint256[] memory ids) external view returns (uint256);\n    function balanceOfUnfertilized(address account, uint256[] memory ids) external view returns (uint256);\n    function lastBalanceOf(address account, uint256 id) external view returns (Balance memory);\n    function lastBalanceOfBatch(address[] memory account, uint256[] memory id) external view returns (Balance[] memory);\n    function setURI(string calldata newuri) external;\n}"
      },
      "contracts/interfaces/IProxyAdmin.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma experimental ABIEncoderV2;\npragma solidity =0.7.6;\ninterface IProxyAdmin {\n    function upgrade(address proxy, address implementation) external;\n}\n"
      },
      "contracts/libraries/Curve/LibBeanMetaCurve.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {LibMetaCurve, IMeta3Curve} from \"./LibMetaCurve.sol\";\nimport {LibCurve} from \"./LibCurve.sol\";\nimport \"contracts/C.sol\";\n\n/**\n * @title LibBeanMetaCurve\n * @author Publius\n * @notice Calculates BDV and deltaB for the BEAN:3CRV Metapool.\n */\nlibrary LibBeanMetaCurve {\n    using SafeMath for uint256;\n\n    uint256 private constant RATE_MULTIPLIER = 1e12; // Bean has 6 Decimals => 1e(18 - delta decimals)\n    uint256 private constant PRECISION = 1e18;\n    uint256 private constant i = 0;\n    uint256 private constant j = 1;\n\n    //////////////////// GETTERS ////////////////////\n\n    /**\n     * @param amount An amount of the BEAN:3CRV LP token.\n     * @dev Calculates the current BDV of BEAN given the balances in the BEAN:3CRV\n     * Metapool. NOTE: assumes that `balances[0]` is BEAN.\n     */\n    function bdv(uint256 amount) internal view returns (uint256) {\n        // By using previous balances and the virtual price, we protect against flash loan\n        uint256[2] memory balances = IMeta3Curve(C.CURVE_BEAN_METAPOOL).get_previous_balances();\n        uint256 virtualPrice = C.curveMetapool().get_virtual_price();\n        uint256[2] memory xp = LibMetaCurve.getXP(balances, RATE_MULTIPLIER);\n\n        uint256 a = C.curveMetapool().A_precise();\n        uint256 D = LibCurve.getD(xp, a);\n        uint256 price = LibCurve.getPrice(xp, a, D, RATE_MULTIPLIER);\n        uint256 totalSupply = (D * PRECISION) / virtualPrice;\n        uint256 beanValue = balances[0].mul(amount).div(totalSupply);\n        uint256 curveValue = xp[1].mul(amount).div(totalSupply).div(price);\n        \n        return beanValue.add(curveValue);\n    }\n\n    function getDeltaB() internal view returns (int256 deltaB) {\n        uint256[2] memory balances = C.curveMetapool().get_balances();\n        uint256 d = getDFroms(balances);\n        deltaB = getDeltaBWithD(balances[0], d);\n    }\n    \n    function getDeltaBWithD(uint256 balance, uint256 D)\n        internal\n        pure\n        returns (int256 deltaB)\n    {\n        uint256 pegBeans = D / 2 / RATE_MULTIPLIER;\n        deltaB = int256(pegBeans) - int256(balance);\n    }\n\n    //////////////////// CURVE HELPERS ////////////////////\n\n    /**\n     * @dev D = the number of LP tokens times the virtual price.\n     * LP supply = D / virtual price. D increases as pool accumulates fees.\n     * D = number of stable tokens in the pool when the pool is balanced. \n     * \n     * Rate multiplier for BEAN is 1e12.\n     * Rate multiplier for 3CRV is virtual price.\n     */\n    function getDFroms(uint256[2] memory balances)\n        internal\n        view\n        returns (uint256)\n    {\n        return LibMetaCurve.getDFroms(\n            C.CURVE_BEAN_METAPOOL,\n            balances,\n            RATE_MULTIPLIER\n        );\n    }\n\n    /**\n     * @dev `xp = balances * RATE_MULTIPLIER`\n     */\n    function getXP(uint256[2] memory balances)\n        internal\n        view\n        returns (uint256[2] memory xp)\n    {\n        xp = LibMetaCurve.getXP(balances, RATE_MULTIPLIER);\n    }\n\n    /**\n     * @dev Convert from `balance` -> `xp0`, which is scaled up by `RATE_MULTIPLIER`.\n     */\n    function getXP0(uint256 balance)\n        internal\n        pure\n        returns (uint256 xp0)\n    {\n        xp0 = balance.mul(RATE_MULTIPLIER);\n    }\n\n    /**\n     * @dev Convert from `xp0` -> `balance`, which is scaled down by `RATE_MULTIPLIER`.\n     */\n    function getX0(uint256 xp0)\n        internal\n        pure\n        returns (uint256 balance0)\n    {\n        balance0 = xp0.div(RATE_MULTIPLIER);\n    }\n}\n"
      },
      "contracts/libraries/Curve/LibCurve.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\n\n/**\n * @title LibCurve\n * @author Publius\n * @notice Low-level Curve swap math for a 2-token StableSwap pool.\n */\nlibrary LibCurve {\n    using SafeMath for uint256;\n\n    uint256 private constant A_PRECISION = 100;\n    uint256 private constant N_COINS = 2;\n    uint256 private constant PRECISION = 1e18;\n    uint256 private constant i = 0;\n    uint256 private constant j = 1;\n\n    /**\n     * @dev Find the change in token `j` given a change in token `i`.\n     */\n    function getPrice(\n        uint256[2] memory xp,\n        uint256 a,\n        uint256 D,\n        uint256 padding\n    ) internal pure returns (uint256) {\n        uint256 x = xp[i] + padding;\n        uint256 y = getY(x, xp, a, D);\n        uint256 dy = xp[j] - y - 1;\n        return dy;\n    }\n\n    function getPrice(\n        uint256[2] memory xp,\n        uint256[2] memory rates,\n        uint256 a,\n        uint256 D\n    ) internal pure returns (uint256) {\n        uint256 x = xp[i] + ((1 * rates[i]) / PRECISION);\n        uint256 y = getY(x, xp, a, D);\n        uint256 dy = xp[j] - y - 1;\n        return dy / 1e6;\n    }\n\n    function getY(\n        uint256 x,\n        uint256[2] memory xp,\n        uint256 a,\n        uint256 D\n    ) internal pure returns (uint256 y) {\n        // Solution is taken from pool contract: 0xc9C32cd16Bf7eFB85Ff14e0c8603cc90F6F2eE49\n        uint256 S_ = 0;\n        uint256 _x = 0;\n        uint256 y_prev = 0;\n        uint256 c = D;\n        uint256 Ann = a * N_COINS;\n\n        for (uint256 _i; _i < N_COINS; ++_i) {\n            if (_i == i) _x = x;\n            else if (_i != j) _x = xp[_i];\n            else continue;\n            S_ += _x;\n            c = (c * D) / (_x * N_COINS);\n        }\n\n        c = (c * D * A_PRECISION) / (Ann * N_COINS);\n        uint256 b = S_ + (D * A_PRECISION) / Ann; // - D\n        y = D;\n\n        for (uint256 _i; _i < 255; ++_i) {\n            y_prev = y;\n            y = (y * y + c) / (2 * y + b - D);\n            if (y > y_prev && y - y_prev <= 1) return y;\n            else if (y_prev - y <= 1) return y;\n        }\n        require(false, \"Price: Convergence false\");\n    }\n\n    function getD(uint256[2] memory xp, uint256 a)\n        internal\n        pure\n        returns (uint256 D)\n    {\n        // Solution is taken from pool contract: 0xc9C32cd16Bf7eFB85Ff14e0c8603cc90F6F2eE49\n        uint256 S;\n        uint256 Dprev;\n        for (uint256 _i; _i < xp.length; ++_i) {\n            S += xp[_i];\n        }\n        if (S == 0) return 0;\n\n        D = S;\n        uint256 Ann = a * N_COINS;\n        for (uint256 _i; _i < 256; ++_i) {\n            uint256 D_P = D;\n            for (uint256 _j; _j < xp.length; ++_j) {\n                D_P = (D_P * D) / (xp[_j] * N_COINS);\n            }\n            Dprev = D;\n            D =\n                (((Ann * S) / A_PRECISION + D_P * N_COINS) * D) /\n                (((Ann - A_PRECISION) * D) / A_PRECISION + (N_COINS + 1) * D_P);\n            if (D > Dprev && D - Dprev <= 1) return D;\n            else if (Dprev - D <= 1) return D;\n        }\n        require(false, \"Price: Convergence false\");\n        return 0;\n    }\n\n    function getYD(\n        uint256 a,\n        uint256 i_,\n        uint256[2] memory xp,\n        uint256 D\n    ) internal pure returns (uint256 y) {\n        // Solution is taken from pool contract: 0xc9C32cd16Bf7eFB85Ff14e0c8603cc90F6F2eE49\n        uint256 S_ = 0;\n        uint256 _x = 0;\n        uint256 y_prev = 0;\n        uint256 c = D;\n        uint256 Ann = a * N_COINS;\n\n        for (uint256 _i; _i < N_COINS; ++_i) {\n            if (_i != i_) _x = xp[_i];\n            else continue;\n            S_ += _x;\n            c = (c * D) / (_x * N_COINS);\n        }\n\n        c = (c * D * A_PRECISION) / (Ann * N_COINS);\n        uint256 b = S_ + (D * A_PRECISION) / Ann; // - D\n        y = D;\n\n        for (uint256 _i; _i < 255; ++_i) {\n            y_prev = y;\n            y = (y * y + c) / (2 * y + b - D);\n            if (y > y_prev && y - y_prev <= 1) return y;\n            else if (y_prev - y <= 1) return y;\n        }\n        require(false, \"Price: Convergence false\");\n    }\n\n    /**\n     * @dev Return the `xp` array for two tokens. Adjusts `balances[0]` by `padding`\n     * and `balances[1]` by `rate / PRECISION`.\n     * \n     * This is provided as a gas optimization when `rates[0] * PRECISION` has been\n     * pre-computed.\n     */\n    function getXP(\n        uint256[2] memory balances,\n        uint256 padding,\n        uint256 rate\n    ) internal pure returns (uint256[2] memory xp) {\n        xp[0] = balances[0].mul(padding);\n        xp[1] = balances[1].mul(rate).div(PRECISION);\n    }\n\n    /**\n     * @dev Return the `xp` array for two tokens. Adjusts `balances[0]` by `rates[0]`\n     * and `balances[1]` by `rates[1] / PRECISION`.\n     */\n    function getXP(\n        uint256[2] memory balances,\n        uint256[2] memory rates\n    ) internal pure returns (uint256[2] memory xp) {\n        xp[0] = balances[0].mul(rates[0]).div(PRECISION);\n        xp[1] = balances[1].mul(rates[1]).div(PRECISION);\n    }\n}\n"
      },
      "contracts/libraries/Curve/LibMetaCurve.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {LibCurve} from \"./LibCurve.sol\";\nimport \"../../C.sol\";\n\n/**\n * @dev Curve Metapool extended interface.\n */\ninterface IMeta3Curve {\n    function A_precise() external view returns (uint256);\n    function get_previous_balances() external view returns (uint256[2] memory);\n    function get_virtual_price() external view returns (uint256);\n}\n\n/**\n * @title LibMetaCurve\n * @author Publius\n * @notice Wraps {LibCurve} with metadata about Curve Metapools, including the\n * `A` parameter and virtual price.\n */\nlibrary LibMetaCurve {\n    using SafeMath for uint256;\n    \n    /**\n     * @dev Used in {LibBeanMetaCurve}.\n     */\n    function getXP(\n        uint256[2] memory balances,\n        uint256 padding\n    ) internal view returns (uint256[2] memory) {\n        return LibCurve.getXP(\n            balances,\n            padding,\n            C.curve3Pool().get_virtual_price()\n        );\n    }\n\n    /**\n     * @dev Used in {LibBeanMetaCurve}.\n     */\n    function getDFroms(\n        address pool,\n        uint256[2] memory balances,\n        uint256 padding\n    ) internal view returns (uint256) {\n        return LibCurve.getD(\n            getXP(balances, padding),\n            IMeta3Curve(pool).A_precise()\n        );\n    }\n\n}\n"
      },
      "contracts/libraries/Decimal.sol": {
        "content": "/*\n SPDX-License-Identifier: MIT\n*/\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport { SafeMath } from \"@openzeppelin/contracts/math/SafeMath.sol\";\n\n/**\n * @title Decimal\n * @author dYdX\n *\n * Library that defines a fixed-point number with 18 decimal places.\n */\nlibrary Decimal {\n    using SafeMath for uint256;\n\n    // ============ Constants ============\n\n    uint256 constant BASE = 10**18;\n\n    // ============ Structs ============\n\n\n    struct D256 {\n        uint256 value;\n    }\n\n    // ============ Static Functions ============\n\n    function zero()\n    internal\n    pure\n    returns (D256 memory)\n    {\n        return D256({ value: 0 });\n    }\n\n    function one()\n    internal\n    pure\n    returns (D256 memory)\n    {\n        return D256({ value: BASE });\n    }\n\n    function from(\n        uint256 a\n    )\n    internal\n    pure\n    returns (D256 memory)\n    {\n        return D256({ value: a.mul(BASE) });\n    }\n\n    function ratio(\n        uint256 a,\n        uint256 b\n    )\n    internal\n    pure\n    returns (D256 memory)\n    {\n        return D256({ value: getPartial(a, BASE, b) });\n    }\n\n    // ============ Self Functions ============\n\n    function add(\n        D256 memory self,\n        uint256 b\n    )\n    internal\n    pure\n    returns (D256 memory)\n    {\n        return D256({ value: self.value.add(b.mul(BASE)) });\n    }\n\n    function sub(\n        D256 memory self,\n        uint256 b\n    )\n    internal\n    pure\n    returns (D256 memory)\n    {\n        return D256({ value: self.value.sub(b.mul(BASE)) });\n    }\n\n    function sub(\n        D256 memory self,\n        uint256 b,\n        string memory reason\n    )\n    internal\n    pure\n    returns (D256 memory)\n    {\n        return D256({ value: self.value.sub(b.mul(BASE), reason) });\n    }\n\n    function mul(\n        D256 memory self,\n        uint256 b\n    )\n    internal\n    pure\n    returns (D256 memory)\n    {\n        return D256({ value: self.value.mul(b) });\n    }\n\n    function div(\n        D256 memory self,\n        uint256 b\n    )\n    internal\n    pure\n    returns (D256 memory)\n    {\n        return D256({ value: self.value.div(b) });\n    }\n\n    function pow(\n        D256 memory self,\n        uint256 b\n    )\n    internal\n    pure\n    returns (D256 memory)\n    {\n        if (b == 0) {\n            return one();\n        }\n\n        D256 memory temp = D256({ value: self.value });\n        for (uint256 i = 1; i < b; ++i) {\n            temp = mul(temp, self);\n        }\n\n        return temp;\n    }\n\n    function add(\n        D256 memory self,\n        D256 memory b\n    )\n    internal\n    pure\n    returns (D256 memory)\n    {\n        return D256({ value: self.value.add(b.value) });\n    }\n\n    function sub(\n        D256 memory self,\n        D256 memory b\n    )\n    internal\n    pure\n    returns (D256 memory)\n    {\n        return D256({ value: self.value.sub(b.value) });\n    }\n\n    function sub(\n        D256 memory self,\n        D256 memory b,\n        string memory reason\n    )\n    internal\n    pure\n    returns (D256 memory)\n    {\n        return D256({ value: self.value.sub(b.value, reason) });\n    }\n\n    function mul(\n        D256 memory self,\n        D256 memory b\n    )\n    internal\n    pure\n    returns (D256 memory)\n    {\n        return D256({ value: getPartial(self.value, b.value, BASE) });\n    }\n\n    function div(\n        D256 memory self,\n        D256 memory b\n    )\n    internal\n    pure\n    returns (D256 memory)\n    {\n        return D256({ value: getPartial(self.value, BASE, b.value) });\n    }\n\n    function equals(D256 memory self, D256 memory b) internal pure returns (bool) {\n        return self.value == b.value;\n    }\n\n    function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {\n        return compareTo(self, b) == 2;\n    }\n\n    function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {\n        return compareTo(self, b) == 0;\n    }\n\n    function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {\n        return compareTo(self, b) > 0;\n    }\n\n    function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {\n        return compareTo(self, b) < 2;\n    }\n\n    function isZero(D256 memory self) internal pure returns (bool) {\n        return self.value == 0;\n    }\n\n    function asUint256(D256 memory self) internal pure returns (uint256) {\n        return self.value.div(BASE);\n    }\n\n    // ============ Core Methods ============\n\n    function getPartial(\n        uint256 target,\n        uint256 numerator,\n        uint256 denominator\n    )\n    private\n    pure\n    returns (uint256)\n    {\n        return target.mul(numerator).div(denominator);\n    }\n\n    function compareTo(\n        D256 memory a,\n        D256 memory b\n    )\n    private\n    pure\n    returns (uint256)\n    {\n        if (a.value == b.value) {\n            return 1;\n        }\n        return a.value > b.value ? 2 : 0;\n    }\n}\n"
      },
      "contracts/libraries/LibAppStorage.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\n// Import all of AppStorage to give importers of LibAppStorage access to {Account}, etc.\nimport \"../beanstalk/AppStorage.sol\";\n\n/**\n * @title LibAppStorage \n * @author Publius\n * @notice Allows libaries to access Beanstalk's state.\n */\nlibrary LibAppStorage {\n    function diamondStorage() internal pure returns (AppStorage storage ds) {\n        assembly {\n            ds.slot := 0\n        }\n    }\n}\n"
      },
      "contracts/libraries/LibLockedUnderlying.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {AppStorage, LibAppStorage} from \"./LibAppStorage.sol\";\n\n/**\n * @title LibLockedUnderlying\n * @author Brendan\n * @notice Library to calculate the number of Underlying Tokens that would be locked if all of\n * the Unripe Tokens are Chopped.\n */\nlibrary LibLockedUnderlying {\n    using SafeMath for uint256;\n\n    /**\n     * @notice Return the amount of Underlying Tokens that would be locked if all of the Unripe Tokens\n     * were chopped.\n     */\n    function getLockedUnderlying(\n        address unripeToken,\n        uint256 recapPercentPaid\n    ) external view returns (uint256 lockedUnderlying) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        return\n            s\n                .u[unripeToken]\n                .balanceOfUnderlying\n                .mul(getPercentLockedUnderlying(unripeToken, recapPercentPaid))\n                .div(1e18);\n    }\n\n    /**\n     * @notice Return the % of Underlying Tokens that would be locked if all of the Unripe Tokens\n     * were chopped.\n     * @param unripeToken The address of the Unripe Token\n     * @param recapPercentPaid The % of Sprouts that have been Rinsed or are Rinsable.\n     * Should have 6 decimal precision.\n     *\n     * @dev Solves the below equation for N_{⌈U/i⌉}:\n     * N_{t+1} = N_t - i * R * N_t / (U - i * t)\n     * where:\n     *  - N_t is the number of Underlying Tokens at step t\n     *  - U is the starting number of Unripe Tokens\n     *  - R is the % of Sprouts that are Rinsable or Rinsed\n     *  - i is the number of Unripe Beans that are chopped at each step. i ~= 46,659 is used as this is aboutr\n     *    the average Unripe Beans held per Farmer with a non-zero balance.\n     *\n     * The equation is solved by using a lookup table of N_{⌈U/i⌉} values for different values of\n     * U and R (The solution is independent of N) as solving iteratively is too computationally\n     * expensive and there is no more efficient way to solve the equation.\n     */\n    function getPercentLockedUnderlying(\n        address unripeToken,\n        uint256 recapPercentPaid\n    ) private view returns (uint256 percentLockedUnderlying) {\n        uint256 unripeSupply = IERC20(unripeToken).totalSupply();\n        if (unripeSupply < 1_000_000) return 0; // If < 1,000,000 Assume all supply is unlocked.\n        if (unripeSupply > 5_000_000) {\n            if (unripeSupply > 10_000_000) {\n                if (recapPercentPaid > 0.1e6) {\n                    if (recapPercentPaid > 0.21e6) {\n                        if (recapPercentPaid > 0.38e6) {\n                            if (recapPercentPaid > 0.45e6) {\n                                return 0.000106800755371506e18; // 90,000,000, 0.9\n                            } else {\n                                return 0.019890729697455534e18; // 90,000,000, 0.45\n                            }\n                        } else if (recapPercentPaid > 0.29e6) {\n                            if (recapPercentPaid > 0.33e6) {\n                                return 0.038002726385307994e18; // 90,000,000 0.38\n                            } else {\n                                return 0.05969915165233464e18; // 90,000,000 0.33\n                            }\n                        } else if (recapPercentPaid > 0.25e6) {\n                            if (recapPercentPaid > 0.27e6) {\n                                return 0.08520038853809475e18; // 90,000,000 0.29\n                            } else {\n                                return 0.10160827712172482e18; // 90,000,000 0.27\n                            }\n                        } else {\n                            if (recapPercentPaid > 0.23e6) {\n                                return 0.1210446758987509e18; // 90,000,000 0.25\n                            } else {\n                                return 0.14404919400935834e18; // 90,000,000 0.23\n                            }\n                        }\n                    } else {\n                        if (recapPercentPaid > 0.17e6) {\n                            if (recapPercentPaid > 0.19e6) {\n                                return 0.17125472579906187e18; // 90,000,000, 0.21\n                            } else {\n                                return 0.2034031571094802e18; // 90,000,000, 0.19\n                            }\n                        } else if (recapPercentPaid > 0.14e6) {\n                            if (recapPercentPaid > 0.15e6) {\n                                return 0.24136365460186238e18; // 90,000,000 0.17\n                            } else {\n                                return 0.2861539540121635e18; // 90,000,000 0.15\n                            }\n                        } else if (recapPercentPaid > 0.12e6) {\n                            if (recapPercentPaid > 0.13e6) {\n                                return 0.3114749615435798e18; // 90,000,000 0.14\n                            } else {\n                                return 0.3389651289211062e18; // 90,000,000 0.13\n                            }\n                        } else {\n                            if (recapPercentPaid > 0.11e6) {\n                                return 0.3688051484970447e18; // 90,000,000 0.12\n                            } else {\n                                return 0.4011903974987394e18; // 90,000,000 0.11\n                            }\n                        }\n                    }\n                } else {\n                    if (recapPercentPaid > 0.04e6) {\n                        if (recapPercentPaid > 0.08e6) {\n                            if (recapPercentPaid > 0.09e6) {\n                                return 0.4363321054081788e18; // 90,000,000, 0.1\n                            } else {\n                                return 0.4744586123058411e18; // 90,000,000, 0.09\n                            }\n                        } else if (recapPercentPaid > 0.06e6) {\n                            if (recapPercentPaid > 0.07e6) {\n                                return 0.5158167251384363e18; // 90,000,000 0.08\n                            } else {\n                                return 0.560673179393784e18; // 90,000,000 0.07\n                            }\n                        } else if (recapPercentPaid > 0.05e6) {\n                            if (recapPercentPaid > 0.055e6) {\n                                return 0.6093162142284054e18; // 90,000,000 0.06\n                            } else {\n                                return 0.6351540690346162e18; // 90,000,000 0.055\n                            }\n                        } else {\n                            if (recapPercentPaid > 0.045e6) {\n                                return 0.6620572696973799e18; // 90,000,000 0.05\n                            } else {\n                                return 0.6900686713435757e18; // 90,000,000 0.045\n                            }\n                        }\n                    } else {\n                        if (recapPercentPaid > 0.03e6) {\n                            if (recapPercentPaid > 0.035e6) {\n                                return 0.7192328153846157e18; // 90,000,000, 0.04\n                            } else {\n                                return 0.7495959945573412e18; // 90,000,000, 0.035\n                            }\n                        } else if (recapPercentPaid > 0.02e6) {\n                            if (recapPercentPaid > 0.025e6) {\n                                return 0.7812063204281795e18; // 90,000,000 0.03\n                            } else {\n                                return 0.8141137934523504e18; // 90,000,000 0.025\n                            }\n                        } else if (recapPercentPaid > 0.01e6) {\n                            if (recapPercentPaid > 0.015e6) {\n                                return 0.8483703756831885e18; // 90,000,000 0.02\n                            } else {\n                                return 0.8840300662301638e18; // 90,000,000 0.015\n                            }\n                        } else {\n                            if (recapPercentPaid > 0.005e6) {\n                                return 0.921148979567821e18; // 90,000,000 0.01\n                            } else {\n                                return 0.9597854268015467e18; // 90,000,000 0.005\n                            }\n                        }\n                    }\n                }\n            } else {\n                // > 5,000,000\n                if (recapPercentPaid > 0.1e6) {\n                    if (recapPercentPaid > 0.21e6) {\n                        if (recapPercentPaid > 0.38e6) {\n                            if (recapPercentPaid > 0.45e6) {\n                                return 0.000340444522821781e18; // 10,000,000, 0.9\n                            } else {\n                                return 0.04023093970853808e18; // 10,000,000, 0.45\n                            }\n                        } else if (recapPercentPaid > 0.29e6) {\n                            if (recapPercentPaid > 0.33e6) {\n                                return 0.06954881077191022e18; // 10,000,000 0.38\n                            } else {\n                                return 0.10145116013499655e18; // 10,000,000 0.33\n                            }\n                        } else if (recapPercentPaid > 0.25e6) {\n                            if (recapPercentPaid > 0.27e6) {\n                                return 0.13625887314323348e18; // 10,000,000 0.29\n                            } else {\n                                return 0.15757224609763754e18; // 10,000,000 0.27\n                            }\n                        } else {\n                            if (recapPercentPaid > 0.23e6) {\n                                return 0.18197183407669726e18; // 10,000,000 0.25\n                            } else {\n                                return 0.20987581330872107e18; // 10,000,000 0.23\n                            }\n                        }\n                    } else {\n                        if (recapPercentPaid > 0.17e6) {\n                            if (recapPercentPaid > 0.19e6) {\n                                return 0.24175584233885106e18; // 10,000,000, 0.21\n                            } else {\n                                return 0.27814356260741413e18; // 10,000,000, 0.19\n                            }\n                        } else if (recapPercentPaid > 0.14e6) {\n                            if (recapPercentPaid > 0.15e6) {\n                                return 0.3196378540296301e18; // 10,000,000 0.17\n                            } else {\n                                return 0.36691292973511136e18; // 10,000,000 0.15\n                            }\n                        } else if (recapPercentPaid > 0.1e6) {\n                            if (recapPercentPaid > 0.13e6) {\n                                return 0.3929517529835418e18; // 10,000,000 0.14\n                            } else {\n                                return 0.4207273631610372e18; // 10,000,000 0.13\n                            }\n                        } else {\n                            if (recapPercentPaid > 0.11e6) {\n                                return 0.450349413795883e18; // 10,000,000 0.12\n                            } else {\n                                return 0.4819341506654745e18; // 10,000,000 0.11\n                            }\n                        }\n                    }\n                } else {\n                    if (recapPercentPaid > 0.04e6) {\n                        if (recapPercentPaid > 0.08e6) {\n                            if (recapPercentPaid > 0.09e6) {\n                                return 0.5156047910307769e18; // 10,000,000, 0.1\n                            } else {\n                                return 0.551491923831086e18; // 10,000,000, 0.09\n                            }\n                        } else if (recapPercentPaid > 0.06e6) {\n                            if (recapPercentPaid > 0.07e6) {\n                                return 0.5897339319558434e18; // 10,000,000 0.08\n                            } else {\n                                return 0.6304774377677631e18; // 10,000,000 0.07\n                            }\n                        } else if (recapPercentPaid > 0.05e6) {\n                            if (recapPercentPaid > 0.055e6) {\n                                return 0.6738777731119263e18; // 10,000,000 0.06\n                            } else {\n                                return 0.6966252960203008e18; // 10,000,000 0.055\n                            }\n                        } else {\n                            if (recapPercentPaid > 0.045e6) {\n                                return 0.7200994751088836e18; // 10,000,000 0.05\n                            } else {\n                                return 0.7443224016328813e18; // 10,000,000 0.045\n                            }\n                        }\n                    } else {\n                        if (recapPercentPaid > 0.03e6) {\n                            if (recapPercentPaid > 0.035e6) {\n                                return 0.7693168090963867e18; // 10,000,000, 0.04\n                            } else {\n                                return 0.7951060911805916e18; // 10,000,000, 0.035\n                            }\n                        } else if (recapPercentPaid > 0.02e6) {\n                            if (recapPercentPaid > 0.025e6) {\n                                return 0.8217143201541763e18; // 10,000,000 0.03\n                            } else {\n                                return 0.8491662657783823e18; // 10,000,000 0.025\n                            }\n                        } else if (recapPercentPaid > 0.01e6) {\n                            if (recapPercentPaid > 0.015e6) {\n                                return 0.8774874147196358e18; // 10,000,000 0.02\n                            } else {\n                                return 0.9067039904828691e18; // 10,000,000 0.015\n                            }\n                        } else {\n                            if (recapPercentPaid > 0.005e6) {\n                                return 0.9368429738790524e18; // 10,000,000 0.01\n                            } else {\n                                return 0.9679321240407666e18; // 10,000,000 0.005\n                            }\n                        }\n                    }\n                }\n            }\n        } else {\n            if (unripeSupply > 1_000_000) {\n                if (recapPercentPaid > 0.1e6) {\n                    if (recapPercentPaid > 0.21e6) {\n                        if (recapPercentPaid > 0.38e6) {\n                            if (recapPercentPaid > 0.45e6) {\n                                return 0.000946395082480844e18; // 3,000,000, 0.9\n                            } else {\n                                return 0.06786242725985348e18; // 3,000,000, 0.45\n                            }\n                        } else if (recapPercentPaid > 0.29e6) {\n                            if (recapPercentPaid > 0.33e6) {\n                                return 0.10822315472628707e18; // 3,000,000 0.38\n                            } else {\n                                return 0.14899524306327216e18; // 3,000,000 0.33\n                            }\n                        } else if (recapPercentPaid > 0.25e6) {\n                            if (recapPercentPaid > 0.27e6) {\n                                return 0.1910488239684135e18; // 3,000,000 0.29\n                            } else {\n                                return 0.215863137234529e18; // 3,000,000 0.27\n                            }\n                        } else {\n                            if (recapPercentPaid > 0.23e6) {\n                                return 0.243564628757033e18; // 3,000,000 0.25\n                            } else {\n                                return 0.2744582675491247e18; // 3,000,000 0.23\n                            }\n                        }\n                    } else {\n                        if (recapPercentPaid > 0.17e6) {\n                            if (recapPercentPaid > 0.19e6) {\n                                return 0.3088786047254358e18; // 3,000,000, 0.21\n                            } else {\n                                return 0.3471924328319608e18; // 3,000,000, 0.19\n                            }\n                        } else if (recapPercentPaid > 0.14e6) {\n                            if (recapPercentPaid > 0.15e6) {\n                                return 0.38980166833777796e18; // 3,000,000 0.17\n                            } else {\n                                return 0.4371464748698771e18; // 3,000,000 0.15\n                            }\n                        } else if (recapPercentPaid > 0.12e6) {\n                            if (recapPercentPaid > 0.13e6) {\n                                return 0.46274355346663876e18; // 3,000,000 0.14\n                            } else {\n                                return 0.4897086460787351e18; // 3,000,000 0.13\n                            }\n                        } else {\n                            if (recapPercentPaid > 0.11e6) {\n                                return 0.518109082463349e18; // 3,000,000 0.12\n                            } else {\n                                return 0.5480152684204499e18; // 3,000,000 0.11\n                            }\n                        }\n                    }\n                } else {\n                    if (recapPercentPaid > 0.04e6) {\n                        if (recapPercentPaid > 0.08e6) {\n                            if (recapPercentPaid > 0.09e6) {\n                                return 0.5795008171102514e18; // 3,000,000, 0.1\n                            } else {\n                                return 0.6126426856374751e18; // 3,000,000, 0.09\n                            }\n                        } else if (recapPercentPaid > 0.06e6) {\n                            if (recapPercentPaid > 0.07e6) {\n                                return 0.6475213171017626e18; // 3,000,000 0.08\n                            } else {\n                                return 0.6842207883207123e18; // 3,000,000 0.07\n                            }\n                        } else if (recapPercentPaid > 0.05e6) {\n                            if (recapPercentPaid > 0.055e6) {\n                                return 0.7228289634394097e18; // 3,000,000 0.06\n                            } else {\n                                return 0.742877347280416e18; // 3,000,000 0.055\n                            }\n                        } else {\n                            if (recapPercentPaid > 0.045e6) {\n                                return 0.7634376536479606e18; // 3,000,000 0.05\n                            } else {\n                                return 0.784522002909275e18; // 3,000,000 0.045\n                            }\n                        }\n                    } else {\n                        if (recapPercentPaid > 0.03e6) {\n                            if (recapPercentPaid > 0.035e6) {\n                                return 0.8061427832364296e18; // 3,000,000, 0.04\n                            } else {\n                                return 0.8283126561589187e18; // 3,000,000, 0.035\n                            }\n                        } else if (recapPercentPaid > 0.02e6) {\n                            if (recapPercentPaid > 0.025e6) {\n                                return 0.8510445622247672e18; // 3,000,000 0.03\n                            } else {\n                                return 0.8743517267721741e18; // 3,000,000 0.025\n                            }\n                        } else if (recapPercentPaid > 0.01e6) {\n                            if (recapPercentPaid > 0.015e6) {\n                                return 0.8982476658137254e18; // 3,000,000 0.02\n                            } else {\n                                return 0.9227461920352636e18; // 3,000,000 0.015\n                            }\n                        } else {\n                            if (recapPercentPaid > 0.005e6) {\n                                return 0.9478614209115208e18; // 3,000,000 0.01\n                            } else {\n                                return 0.9736077769406731e18; // 3,000,000 0.005\n                            }\n                        }\n                    }\n                }\n            } else {\n                if (recapPercentPaid > 0.1e6) {\n                    if (recapPercentPaid > 0.21e6) {\n                        if (recapPercentPaid > 0.38e6) {\n                            if (recapPercentPaid > 0.45e6) {\n                                return 0.003360632002379016e18; // 1,000,000, 0.9\n                            } else {\n                                return 0.12071031956650236e18; // 1,000,000, 0.45\n                            }\n                        } else if (recapPercentPaid > 0.29e6) {\n                            if (recapPercentPaid > 0.33e6) {\n                                return 0.1752990554517151e18; // 1,000,000 0.38\n                            } else {\n                                return 0.22598948369141458e18; // 1,000,000 0.33\n                            }\n                        } else if (recapPercentPaid > 0.25e6) {\n                            if (recapPercentPaid > 0.27e6) {\n                                return 0.27509697387157794e18; // 1,000,000 0.29\n                            } else {\n                                return 0.3029091410266461e18; // 1,000,000 0.27\n                            }\n                        } else {\n                            if (recapPercentPaid > 0.23e6) {\n                                return 0.33311222196618273e18; // 1,000,000 0.25\n                            } else {\n                                return 0.36588364748950297e18; // 1,000,000 0.23\n                            }\n                        }\n                    } else {\n                        if (recapPercentPaid > 0.17e6) {\n                            if (recapPercentPaid > 0.19e6) {\n                                return 0.40141235983370593e18; // 1,000,000, 0.21\n                            } else {\n                                return 0.43989947169522015e18; // 1,000,000, 0.19\n                            }\n                        } else if (recapPercentPaid > 0.14e6) {\n                            if (recapPercentPaid > 0.15e6) {\n                                return 0.4815589587559236e18; // 1,000,000 0.17\n                            } else {\n                                return 0.5266183872325827e18; // 1,000,000 0.15\n                            }\n                        } else if (recapPercentPaid > 0.12e6) {\n                            if (recapPercentPaid > 0.13e6) {\n                                return 0.5504980973828455e18; // 1,000,000 0.14\n                            } else {\n                                return 0.5753196780298556e18; // 1,000,000 0.13\n                            }\n                        } else {\n                            if (recapPercentPaid > 0.11e6) {\n                                return 0.6011157438454372e18; // 1,000,000 0.12\n                            } else {\n                                return 0.6279199091408495e18; // 1,000,000 0.11\n                            }\n                        }\n                    }\n                } else {\n                    if (recapPercentPaid > 0.04e6) {\n                        if (recapPercentPaid > 0.08e6) {\n                            if (recapPercentPaid > 0.09e6) {\n                                return 0.6557668151543954e18; // 1,000,000, 0.1\n                            } else {\n                                return 0.6846921580052533e18; // 1,000,000, 0.09\n                            }\n                        } else if (recapPercentPaid > 0.06e6) {\n                            if (recapPercentPaid > 0.07e6) {\n                                return 0.7147327173281093e18; // 1,000,000 0.08\n                            } else {\n                                return 0.745926385603471e18; // 1,000,000 0.07\n                            }\n                        } else if (recapPercentPaid > 0.05e6) {\n                            if (recapPercentPaid > 0.055e6) {\n                                return 0.7783121981988174e18; // 1,000,000 0.06\n                            } else {\n                                return 0.7949646772335068e18; // 1,000,000 0.055\n                            }\n                        } else {\n                            if (recapPercentPaid > 0.045e6) {\n                                return 0.8119303641360465e18; // 1,000,000 0.05\n                            } else {\n                                return 0.8292144735871585e18; // 1,000,000 0.045\n                            }\n                        }\n                    } else {\n                        if (recapPercentPaid > 0.03e6) {\n                            if (recapPercentPaid > 0.035e6) {\n                                return 0.8468222976009872e18; // 1,000,000, 0.04\n                            } else {\n                                return 0.8647592065514869e18; // 1,000,000, 0.035\n                            }\n                        } else if (recapPercentPaid > 0.02e6) {\n                            if (recapPercentPaid > 0.025e6) {\n                                return 0.8830306502110374e18; // 1,000,000 0.03\n                            } else {\n                                return 0.9016421588014247e18; // 1,000,000 0.025\n                            }\n                        } else if (recapPercentPaid > 0.01e6) {\n                            if (recapPercentPaid > 0.015e6) {\n                                return 0.9205993440573136e18; // 1,000,000 0.02\n                            } else {\n                                return 0.9399079003023474e18; // 1,000,000 0.015\n                            }\n                        } else {\n                            if (recapPercentPaid > 0.005e6) {\n                                return 0.959573605538012e18; // 1,000,000 0.01\n                            } else {\n                                return 0.9796023225453983e18; // 1,000,000 0.005\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n"
      },
      "contracts/libraries/LibSafeMath128.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @author Publius\n * @title LibSafeMath128 is a uint128 variation of Open Zeppelin's Safe Math library.\n**/\nlibrary LibSafeMath128 {\n    /**\n     * @dev Returns the addition of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryAdd(uint128 a, uint128 b) internal pure returns (bool, uint128) {\n        uint128 c = a + b;\n        if (c < a) return (false, 0);\n        return (true, c);\n    }\n\n    /**\n     * @dev Returns the substraction of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function trySub(uint128 a, uint128 b) internal pure returns (bool, uint128) {\n        if (b > a) return (false, 0);\n        return (true, a - b);\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryMul(uint128 a, uint128 b) internal pure returns (bool, uint128) {\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        uint128 c = a * b;\n        if (c / a != b) return (false, 0);\n        return (true, c);\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a division by zero flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryDiv(uint128 a, uint128 b) internal pure returns (bool, uint128) {\n        if (b == 0) return (false, 0);\n        return (true, a / b);\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryMod(uint128 a, uint128 b) internal pure returns (bool, uint128) {\n        if (b == 0) return (false, 0);\n        return (true, a % b);\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `+` operator.\n     *\n     * Requirements:\n     *\n     * - Addition cannot overflow.\n     */\n    function add(uint128 a, uint128 b) internal pure returns (uint128) {\n        uint128 c = a + b;\n        require(c >= a, \"SafeMath: addition overflow\");\n        return c;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting on\n     * overflow (when the result is negative).\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     *\n     * - Subtraction cannot overflow.\n     */\n    function sub(uint128 a, uint128 b) internal pure returns (uint128) {\n        require(b <= a, \"SafeMath: subtraction overflow\");\n        return a - b;\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `*` operator.\n     *\n     * Requirements:\n     *\n     * - Multiplication cannot overflow.\n     */\n    function mul(uint128 a, uint128 b) internal pure returns (uint128) {\n        if (a == 0) return 0;\n        uint128 c = a * b;\n        require(c / a == b, \"SafeMath: multiplication overflow\");\n        return c;\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers, reverting on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity's `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function div(uint128 a, uint128 b) internal pure returns (uint128) {\n        require(b > 0, \"SafeMath: division by zero\");\n        return a / b;\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * reverting when dividing by zero.\n     *\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function mod(uint128 a, uint128 b) internal pure returns (uint128) {\n        require(b > 0, \"SafeMath: modulo by zero\");\n        return a % b;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n     * overflow (when the result is negative).\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {trySub}.\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     *\n     * - Subtraction cannot overflow.\n     */\n    function sub(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {\n        require(b <= a, errorMessage);\n        return a - b;\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n     * division by zero. The result is rounded towards zero.\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {tryDiv}.\n     *\n     * Counterpart to Solidity's `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function div(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {\n        require(b > 0, errorMessage);\n        return a / b;\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * reverting with custom message when dividing by zero.\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {tryMod}.\n     *\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function mod(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {\n        require(b > 0, errorMessage);\n        return a % b;\n    }\n}\n"
      },
      "contracts/libraries/LibUnripe.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {IBean} from \"../interfaces/IBean.sol\";\nimport {AppStorage, LibAppStorage} from \"./LibAppStorage.sol\";\nimport {C} from \"../C.sol\";\nimport {LibWell} from \"./Well/LibWell.sol\";\nimport {Call, IWell} from \"contracts/interfaces/basin/IWell.sol\";\nimport {IWellFunction} from \"contracts/interfaces/basin/IWellFunction.sol\";\nimport {LibLockedUnderlying} from \"./LibLockedUnderlying.sol\";\n\n/**\n * @title LibUnripe\n * @author Publius\n * @notice Library for handling functionality related to Unripe Tokens and their Ripe Tokens.\n */\nlibrary LibUnripe {\n    using SafeMath for uint256;\n\n    event ChangeUnderlying(address indexed token, int256 underlying);\n    event SwitchUnderlyingToken(address indexed token, address indexed underlyingToken);\n\n    uint256 constant DECIMALS = 1e6;\n\n    /**\n     * @notice Returns the percentage that Unripe Beans have been recapitalized.\n     */\n    function percentBeansRecapped() internal view returns (uint256 percent) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        return\n            s.u[C.UNRIPE_BEAN].balanceOfUnderlying.mul(DECIMALS).div(C.unripeBean().totalSupply());\n    }\n\n    /**\n     * @notice Returns the percentage that Unripe LP have been recapitalized.\n     */\n    function percentLPRecapped() internal view returns (uint256 percent) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        return C.unripeLPPerDollar().mul(s.recapitalized).div(C.unripeLP().totalSupply());\n    }\n\n    /**\n     * @notice Increments the underlying balance of an Unripe Token.\n     * @param token The address of the unripe token.\n     * @param amount The amount of the of the unripe token to be added to the storage reserves\n     */\n    function incrementUnderlying(address token, uint256 amount) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        s.u[token].balanceOfUnderlying = s.u[token].balanceOfUnderlying.add(amount);\n        emit ChangeUnderlying(token, int256(amount));\n    }\n\n    /**\n     * @notice Decrements the underlying balance of an Unripe Token.\n     * @param token The address of the Unripe Token.\n     * @param amount The amount of the of the Unripe Token to be removed from storage reserves\n     */\n    function decrementUnderlying(address token, uint256 amount) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        s.u[token].balanceOfUnderlying = s.u[token].balanceOfUnderlying.sub(amount);\n        emit ChangeUnderlying(token, -int256(amount));\n    }\n\n    /**\n     * @notice Calculates the amount of Ripe Tokens that underly a given amount of Unripe Tokens.\n     * @param unripeToken The address of the Unripe Token\n     * @param unripe The amount of Unripe Tokens.\n     * @return underlying The amount of Ripe Tokens that underly the Unripe Tokens.\n     */\n    function unripeToUnderlying(\n        address unripeToken,\n        uint256 unripe,\n        uint256 supply\n    ) internal view returns (uint256 underlying) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        underlying = s.u[unripeToken].balanceOfUnderlying.mul(unripe).div(supply);\n    }\n\n    /**\n     * @notice Calculates the amount of Unripe Tokens that are underlaid by a given amount of Ripe Tokens.\n     * @param unripeToken The address of the Unripe Tokens.\n     * @param underlying The amount of Ripe Tokens.\n     * @return unripe The amount of the of the Unripe Tokens that are underlaid by the Ripe Tokens.\n     */\n    function underlyingToUnripe(\n        address unripeToken,\n        uint256 underlying\n    ) internal view returns (uint256 unripe) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        unripe = IBean(unripeToken).totalSupply().mul(underlying).div(\n            s.u[unripeToken].balanceOfUnderlying\n        );\n    }\n\n    /**\n     * @notice Adds Ripe Tokens to an Unripe Token. Also, increments the recapitalized\n     * amount proportionally if the Unripe Token is Unripe LP.\n     * @param token The address of the Unripe Token to add Ripe Tokens to.\n     * @param underlying The amount of the of the underlying token to be taken as input.\n     */\n    function addUnderlying(address token, uint256 underlying) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        if (token == C.UNRIPE_LP) {\n            uint256 recapped = underlying.mul(s.recapitalized).div(\n                s.u[C.UNRIPE_LP].balanceOfUnderlying\n            );\n            s.recapitalized = s.recapitalized.add(recapped);\n        }\n        incrementUnderlying(token, underlying);\n    }\n\n    /**\n     * @notice Removes Ripe Tokens from an Unripe Token. Also, decrements the recapitalized\n     * amount proportionally if the Unripe Token is Unripe LP.\n     * @param token The address of the unripe token to be removed.\n     * @param underlying The amount of the of the underlying token to be removed.\n     */\n    function removeUnderlying(address token, uint256 underlying) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        if (token == C.UNRIPE_LP) {\n            uint256 recapped = underlying.mul(s.recapitalized).div(\n                s.u[C.UNRIPE_LP].balanceOfUnderlying\n            );\n            s.recapitalized = s.recapitalized.sub(recapped);\n        }\n        decrementUnderlying(token, underlying);\n    }\n\n    /**\n     * @dev Switches the underlying token of an unripe token.\n     * Should only be called if `s.u[unripeToken].balanceOfUnderlying == 0`.\n     */\n    function switchUnderlyingToken(address unripeToken, address newUnderlyingToken) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        s.u[unripeToken].underlyingToken = newUnderlyingToken;\n        emit SwitchUnderlyingToken(unripeToken, newUnderlyingToken);\n    }\n\n    function _getPenalizedUnderlying(\n        address unripeToken,\n        uint256 amount,\n        uint256 supply\n    ) internal view returns (uint256 redeem) {\n        require(isUnripe(unripeToken), \"not vesting\");\n        uint256 sharesBeingRedeemed = getRecapPaidPercentAmount(amount);\n        redeem = _getUnderlying(unripeToken, sharesBeingRedeemed, supply);\n    }\n\n    /**\n     * @notice Calculates the the amount of Ripe Tokens that would be paid out if\n     * all Unripe Tokens were Chopped at the current Chop Rate.\n     */\n    function _getTotalPenalizedUnderlying(\n        address unripeToken\n    ) internal view returns (uint256 redeem) {\n        require(isUnripe(unripeToken), \"not vesting\");\n        uint256 supply = IERC20(unripeToken).totalSupply();\n        redeem = _getUnderlying(unripeToken, getRecapPaidPercentAmount(supply), supply);\n    }\n\n    /**\n     * @notice Returns the amount of beans that are locked in the unripe token.\n     * @dev Locked beans are the beans that are forfeited if the unripe token is chopped.\n     * @param reserves the reserves of the LP that underly the unripe token.\n     * @dev reserves are used as a parameter for gas effiency purposes (see LibEvaluate.calcLPToSupplyRatio}.\n     */\n    function getLockedBeans(\n        uint256[] memory reserves\n    ) internal view returns (uint256 lockedAmount) {\n        lockedAmount = LibLockedUnderlying\n            .getLockedUnderlying(C.UNRIPE_BEAN, getRecapPaidPercentAmount(1e6))\n            .add(getLockedBeansFromLP(reserves));\n    }\n\n    /**\n     * @notice Returns the amount of beans that are locked in the unripeLP token.\n     * @param reserves the reserves of the LP that underly the unripe token.\n     */\n    function getLockedBeansFromLP(\n        uint256[] memory reserves\n    ) internal view returns (uint256 lockedBeanAmount) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        \n        // if reserves return 0, then skip calculations.\n        if (reserves[0] == 0) return 0;\n        \n        uint256 lockedLpAmount = LibLockedUnderlying.getLockedUnderlying(\n            C.UNRIPE_LP,\n            getRecapPaidPercentAmount(1e6)\n        );\n        address underlying = s.u[C.UNRIPE_LP].underlyingToken;\n        uint256 beanIndex = LibWell.getBeanIndexFromWell(underlying);\n\n        // lpTokenSupply is calculated rather than calling totalSupply(),\n        // because the Well's lpTokenSupply is not MEV resistant.\n        Call memory wellFunction = IWell(underlying).wellFunction();\n        uint lpTokenSupply = IWellFunction(wellFunction.target).calcLpTokenSupply(\n            reserves,\n            wellFunction.data\n        );\n        lockedBeanAmount = lockedLpAmount.mul(reserves[beanIndex]).div(lpTokenSupply);\n    }\n\n    /**\n     * @notice Calculates the penalized amount based the amount of Sprouts that are Rinsable\n     * or Rinsed (Fertilized).\n     * @param amount The amount of the Unripe Tokens.\n     * @return penalizedAmount The penalized amount of the Ripe Tokens received from Chopping.\n     */\n    function getRecapPaidPercentAmount(\n        uint256 amount\n    ) internal view returns (uint256 penalizedAmount) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        return s.fertilizedIndex.mul(amount).div(s.unfertilizedIndex);\n    }\n\n    /**\n     * @notice Returns true if the token is unripe.\n     */\n    function isUnripe(address unripeToken) internal view returns (bool unripe) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        unripe = s.u[unripeToken].underlyingToken != address(0);\n    }\n\n    /**\n     * @notice Returns the underlying token amount of the unripe token.\n     */\n    function _getUnderlying(\n        address unripeToken,\n        uint256 amount,\n        uint256 supply\n    ) internal view returns (uint256 redeem) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        redeem = s.u[unripeToken].balanceOfUnderlying.mul(amount).div(supply);\n    }\n}\n"
      },
      "contracts/libraries/Oracle/LibChainlinkOracle.sol": {
        "content": "/**\n * SPDX-License-Identifier: MIT\n **/\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport {C} from \"contracts/C.sol\";\nimport {IChainlinkAggregator} from \"contracts/interfaces/chainlink/IChainlinkAggregator.sol\";\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\n\n/**\n * @title Chainlink Oracle Library\n * @notice Contains functionalty to fetch prices from Chainlink price feeds.\n * @dev currently supports:\n * - ETH/USD price feed\n **/\nlibrary LibChainlinkOracle {\n    using SafeMath for uint256;\n\n    uint256 public constant CHAINLINK_TIMEOUT = 5400; // 60 * 90 = 5400\n\n    IChainlinkAggregator constant priceAggregator =\n        IChainlinkAggregator(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);\n    uint256 constant PRECISION = 1e6; // use 6 decimal precision.\n\n    /**\n     * @dev Returns the most recently reported ETH/USD price from the Chainlink Oracle.\n     * Return value has 6 decimal precision.\n     * Returns 0 if Chainlink's price feed is broken or frozen.\n     **/\n    function getEthUsdPrice() internal view returns (uint256 price) {\n        // First, try to get current decimal precision:\n        uint8 decimals;\n        try priceAggregator.decimals() returns (uint8 _decimals) {\n            // If call to Chainlink succeeds, record the current decimal precision\n            decimals = _decimals;\n        } catch {\n            // If call to Chainlink aggregator reverts, return a price of 0 indicating failure\n            return 0;\n        }\n\n        // Secondly, try to get latest price data:\n        try priceAggregator.latestRoundData() returns (\n            uint80 roundId,\n            int256 answer,\n            uint256 /* startedAt */,\n            uint256 timestamp,\n            uint80 /* answeredInRound */\n        ) {\n            // Check for an invalid roundId that is 0\n            if (roundId == 0) return 0;\n            if (checkForInvalidTimestampOrAnswer(timestamp, answer, block.timestamp)) {\n                return 0;\n            }\n            // Adjust to 6 decimal precision.\n            return uint256(answer).mul(PRECISION).div(10 ** decimals);\n        } catch {\n            // If call to Chainlink aggregator reverts, return a price of 0 indicating failure\n            return 0;\n        }\n    }\n\n    /**\n     * @dev Returns the TWAP ETH/USD price from the Chainlink Oracle over the past `lookback` seconds.\n     * Return value has 6 decimal precision.\n     * Returns 0 if Chainlink's price feed is broken or frozen.\n     **/\n    function getEthUsdTwap(uint256 lookback) internal view returns (uint256 price) {\n        // First, try to get current decimal precision:\n        uint8 decimals;\n        try priceAggregator.decimals() returns (uint8 _decimals) {\n            // If call to Chainlink succeeds, record the current decimal precision\n            decimals = _decimals;\n        } catch {\n            // If call to Chainlink aggregator reverts, return a price of 0 indicating failure\n            return 0;\n        }\n\n        // Secondly, try to get latest price data:\n        try priceAggregator.latestRoundData() returns (\n            uint80 roundId,\n            int256 answer,\n            uint256 /* startedAt */,\n            uint256 timestamp,\n            uint80 /* answeredInRound */\n        ) {\n            // Check for an invalid roundId that is 0\n            if (roundId == 0) return 0;\n            if (checkForInvalidTimestampOrAnswer(timestamp, answer, block.timestamp)) {\n                return 0;\n            }\n\n            uint256 endTimestamp = block.timestamp.sub(lookback);\n            // Check if last round was more than `lookback` ago.\n            if (timestamp <= endTimestamp) {\n                return uint256(answer).mul(PRECISION).div(10 ** decimals);\n            } else {\n                uint256 cumulativePrice;\n                uint256 lastTimestamp = block.timestamp;\n                // Loop through previous rounds and compute cumulative sum until\n                // a round at least `lookback` seconds ago is reached.\n                while (timestamp > endTimestamp) {\n                    cumulativePrice = cumulativePrice.add(\n                        uint256(answer).mul(lastTimestamp.sub(timestamp))\n                    );\n                    roundId -= 1;\n                    try priceAggregator.getRoundData(roundId) returns (\n                        uint80 /* roundId */,\n                        int256 _answer,\n                        uint256 /* startedAt */,\n                        uint256 _timestamp,\n                        uint80 /* answeredInRound */\n                    ) {\n                        if (checkForInvalidTimestampOrAnswer(_timestamp, _answer, timestamp)) {\n                            return 0;\n                        }\n                        lastTimestamp = timestamp;\n                        timestamp = _timestamp;\n                        answer = _answer;\n                    } catch {\n                        // If call to Chainlink aggregator reverts, return a price of 0 indicating failure\n                        return 0;\n                    }\n                }\n                cumulativePrice = cumulativePrice.add(\n                    uint256(answer).mul(lastTimestamp.sub(endTimestamp))\n                );\n                return cumulativePrice.mul(PRECISION).div(10 ** decimals).div(lookback);\n            }\n        } catch {\n            // If call to Chainlink aggregator reverts, return a price of 0 indicating failure\n            return 0;\n        }\n    }\n\n    function checkForInvalidTimestampOrAnswer(\n        uint256 timestamp,\n        int256 answer,\n        uint256 currentTimestamp\n    ) private pure returns (bool) {\n        // Check for an invalid timeStamp that is 0, or in the future\n        if (timestamp == 0 || timestamp > currentTimestamp) return true;\n        // Check if Chainlink's price feed has timed out\n        if (currentTimestamp.sub(timestamp) > CHAINLINK_TIMEOUT) return true;\n        // Check for non-positive price\n        if (answer <= 0) return true;\n    }\n}\n"
      },
      "contracts/libraries/Oracle/LibEthUsdOracle.sol": {
        "content": "/**\n * SPDX-License-Identifier: MIT\n **/\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport {LibChainlinkOracle} from \"./LibChainlinkOracle.sol\";\nimport {LibUniswapOracle} from \"./LibUniswapOracle.sol\";\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {LibAppStorage, AppStorage} from \"contracts/libraries/LibAppStorage.sol\";\nimport {C} from \"contracts/C.sol\";\n/**\n * @title Eth Usd Oracle Library\n * @notice Contains functionalty to fetch a manipulation resistant ETH/USD price.\n * @dev\n * The Oracle uses a greedy approach to return the average price between the\n * current price returned ETH/USD Chainlink Oracle and either the ETH/USDC\n * Uniswap V3 0.05% fee pool and the ETH/USDT Uniswap V3 0.05% fee pool depending\n * on which is closer. \n * \n * If the prices in the ETH/USDC Uniswap V3 0.05% fee pool and USD/USDT Uniswap V3 0.05% fee pool are\n * greater than `MAX_DIFFERENCE` apart, then the oracle uses the Chainlink price to maximize liveness.\n * \n * The approach is greedy as if the ETH/USDC Uniswap price is sufficiently close\n * to the Chainlink Oracle price (See {MAX_GREEDY_DIFFERENCE}), then the Oracle\n * will not check the ETH/USDT Uniswap Price to save gas.\n * \n * The oracle will fail if the Chainlink Oracle is broken or frozen (See: {LibChainlinkOracle}).\n **/\nlibrary LibEthUsdOracle {\n\n    using SafeMath for uint256;\n\n    // The maximum percent different such that it is acceptable to use the greedy approach.\n    uint256 constant MAX_GREEDY_DIFFERENCE = 0.003e18; // 0.3%\n\n    // The maximum percent difference such that the oracle assumes no manipulation is occuring.\n    uint256 constant MAX_DIFFERENCE = 0.01e18; // 1%\n    uint256 constant ONE = 1e18;\n\n    // The lookback used for Uniswap Oracles when querying the instantaneous USD price.\n    uint32 constant INSTANT_LOOKBACK = 900;\n\n    /**\n     * @dev Returns the instantaneous ETH/USD price\n     * Return value has 6 decimal precision.\n     * Returns 0 if the Eth Usd Oracle cannot fetch a manipulation resistant price.\n     **/\n    function getEthUsdPrice() internal view returns (uint256) {\n        return getEthUsdPrice(0);\n    }\n\n    /**\n     * @dev Returns the ETH/USD price with the option of using a TWA lookback.\n     * Use `lookback = 0` for the instantaneous price. `lookback > 0` for a TWAP.\n     * Return value has 6 decimal precision.\n     * Returns 0 if the Eth Usd Oracle cannot fetch a manipulation resistant price.\n     * A lookback of 900 seconds is used in Uniswap V3 pools for instantaneous price queries.\n     * If using a non-zero lookback, it is recommended to use a substantially large\n     * `lookback` (> 900 seconds) to protect against manipulation.\n    **/\n    function getEthUsdPrice(uint256 lookback) internal view returns (uint256) {\n        uint256 chainlinkPrice = lookback > 0 ?\n            LibChainlinkOracle.getEthUsdTwap(lookback) :\n            LibChainlinkOracle.getEthUsdPrice();\n\n        // Check if the chainlink price is broken or frozen.\n        if (chainlinkPrice == 0) return 0;\n\n        // Use a lookback of 900 seconds for an instantaneous price query for manipulation resistance.\n        if (lookback == 0) lookback = INSTANT_LOOKBACK;\n        if (lookback > type(uint32).max) return 0;\n\n        uint256 usdcPrice = LibUniswapOracle.getEthUsdcPrice(uint32(lookback));\n        uint256 usdcChainlinkPercentDiff = getPercentDifference(usdcPrice, chainlinkPrice);\n\n        // Check if the USDC price and the Chainlink Price are sufficiently close enough\n        // to warrant using the greedy approach.\n        if (usdcChainlinkPercentDiff < MAX_GREEDY_DIFFERENCE) {\n            return chainlinkPrice.add(usdcPrice).div(2);\n        }\n\n        uint256 usdtPrice = LibUniswapOracle.getEthUsdtPrice(uint32(lookback));\n        uint256 usdtChainlinkPercentDiff = getPercentDifference(usdtPrice, chainlinkPrice);\n\n        // Check whether the USDT or USDC price is closer to the Chainlink price.\n        if (usdtChainlinkPercentDiff < usdcChainlinkPercentDiff) {\n            // Check whether the USDT price is too far from the Chainlink price.\n            if (usdtChainlinkPercentDiff < MAX_DIFFERENCE) {\n                return chainlinkPrice.add(usdtPrice).div(2);\n            }\n            return chainlinkPrice;\n        } else {\n            // Check whether the USDC price is too far from the Chainlink price.\n            if (usdcChainlinkPercentDiff < MAX_DIFFERENCE) {\n                return chainlinkPrice.add(usdcPrice).div(2);\n            }\n            return chainlinkPrice;\n        }\n    }\n\n    /**\n     * Gets the percent difference between two values with 18 decimal precision.\n     * @dev If x == 0 (Such as in the case of Uniswap Oracle failure), then the percent difference is calculated as 100%.\n     */\n    function getPercentDifference(uint x, uint y) internal pure returns (uint256 percentDifference) {\n        percentDifference = x.mul(ONE).div(y);\n        percentDifference = x > y ?\n            percentDifference - ONE :\n            ONE - percentDifference; // SafeMath unnecessary due to conditional check\n    }\n}\n"
      },
      "contracts/libraries/Oracle/LibUniswapOracle.sol": {
        "content": "/**\n * SPDX-License-Identifier: MIT\n **/\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport {C} from \"contracts/C.sol\";\nimport {OracleLibrary} from \"@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol\";\nimport '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';\n\n/**\n * @title Uniswap Oracle Library\n * @notice Contains functionalty to read prices from Uniswap V3 pools.\n * @dev currently supports:\n * - ETH:USDC price from the ETH:USDC 0.05% pool\n * - ETH:USDT price from the ETH:USDT 0.05% pool\n **/\nlibrary LibUniswapOracle {\n\n    uint128 constant ONE_WETH = 1e18;\n\n    /**\n     * @dev Uses the Uniswap V3 Oracle to get the price of ETH denominated in USDC.\n     * Return value has 6 decimal precision.\n     * Returns 0 if {IUniswapV3Pool.observe} reverts.\n     * It is recommended to use a substantially large `lookback` (at least 900 seconds) to protect\n     * against manipulation.\n     * Note: Uniswap V3 pool oracles are not multi-block MEV resistant.\n     */\n    function getEthUsdcPrice(uint32 lookback) internal view returns (uint256 price) {\n        (bool success, int24 tick) = consult(C.UNIV3_ETH_USDC_POOL, lookback);\n        if (!success) return 0;\n        price = OracleLibrary.getQuoteAtTick(tick, ONE_WETH, C.WETH, C.USDC);\n    }\n\n    /**\n     * @dev Uses the Uniswap V3 Oracle to get the price of ETH denominated in USDT.\n     * Return value has 6 decimal precision.\n     * Returns 0 if {IUniswapV3Pool.observe} reverts.\n     */\n    function getEthUsdtPrice(uint32 lookback) internal view returns (uint256 price) {\n        (bool success, int24 tick) = consult(C.UNIV3_ETH_USDT_POOL, lookback);\n        if (!success) return 0;\n        price = OracleLibrary.getQuoteAtTick(tick, ONE_WETH, C.WETH, C.USDT);\n    }\n\n    /**\n     * @dev A variation of {OracleLibrary.consult} that returns just the arithmetic mean tick and returns 0 on failure\n     * instead of reverting if {IUniswapV3Pool.observe} reverts.\n     * https://github.com/Uniswap/v3-periphery/blob/51f8871aaef2263c8e8bbf4f3410880b6162cdea/contracts/libraries/OracleLibrary.sol\n     */\n    function consult(address pool, uint32 secondsAgo)\n        internal\n        view\n        returns (bool success, int24 arithmeticMeanTick)\n    {\n        require(secondsAgo != 0, 'BP');\n\n        uint32[] memory secondsAgos = new uint32[](2);\n        secondsAgos[0] = secondsAgo;\n        secondsAgos[1] = 0;\n\n        try IUniswapV3Pool(pool).observe(secondsAgos) returns (\n            int56[] memory tickCumulatives,\n            uint160[] memory\n        ) {\n            int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];\n            arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgo);\n            // Always round to negative infinity\n            if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgo != 0)) arithmeticMeanTick--;\n            success = true;\n        } catch {}\n    }\n\n}\n"
      },
      "contracts/libraries/Oracle/LibUsdOracle.sol": {
        "content": "/**\n * SPDX-License-Identifier: MIT\n **/\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport {LibEthUsdOracle} from \"./LibEthUsdOracle.sol\";\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {C} from \"contracts/C.sol\";\n\n/**\n * @title Eth Usd Oracle Library\n * @notice Contains functionalty to fetch the manipulation resistant USD price of different tokens.\n * @dev currently supports:\n * - ETH/USD price\n **/\nlibrary LibUsdOracle {\n\n    using SafeMath for uint256;\n\n    function getUsdPrice(address token) internal view returns (uint256) {\n        return getUsdPrice(token, 0);\n    }\n\n    /**\n     * @dev Returns the price of a given token in in USD with the option of using a lookback.\n     * `lookback` should be 0 if the instantaneous price is desired. Otherwise, it should be the\n     * TWAP lookback in seconds.\n     * If using a non-zero lookback, it is recommended to use a substantially large `lookback`\n     * (> 900 seconds) to protect against manipulation.\n     */\n    function getUsdPrice(address token, uint256 lookback) internal view returns (uint256) {\n        if (token == C.WETH) {\n            uint256 ethUsdPrice = LibEthUsdOracle.getEthUsdPrice(lookback);\n            if (ethUsdPrice == 0) return 0;\n            return uint256(1e24).div(ethUsdPrice);\n        }\n        revert(\"Oracle: Token not supported.\");\n    }\n\n    /**\n     * @notice returns the price of a given token in USD.\n     * @dev if ETH returns 1000 USD, this function returns 1000 \n     * (ignoring decimal precision)\n     */\n    function getTokenPrice(address token) internal view returns (uint256) {\n         if (token == C.WETH) {\n            uint256 ethUsdPrice = LibEthUsdOracle.getEthUsdPrice();\n            if (ethUsdPrice == 0) return 0;\n            return ethUsdPrice;\n        }\n        revert(\"Oracle: Token not supported.\");\n    }\n\n}\n"
      },
      "contracts/libraries/Well/LibWell.sol": {
        "content": "/*\n SPDX-License-Identifier: MIT\n*/\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {ICumulativePump} from \"contracts/interfaces/basin/pumps/ICumulativePump.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IWell} from \"contracts/interfaces/basin/IWell.sol\";\nimport {C} from \"contracts/C.sol\";\nimport {AppStorage, LibAppStorage, Storage} from \"../LibAppStorage.sol\";\nimport {LibUsdOracle} from \"contracts/libraries/Oracle/LibUsdOracle.sol\";\nimport {LibSafeMath128} from \"contracts/libraries/LibSafeMath128.sol\";\n\n/**\n * @title Well Library\n * Contains helper functions for common Well related functionality.\n **/\nlibrary LibWell {\n    using SafeMath for uint256;\n    using LibSafeMath128 for uint128;\n\n    // The BDV Selector that all Wells should be whitelisted with.\n    bytes4 internal constant WELL_BDV_SELECTOR = 0xc84c7727;\n\n    function getRatiosAndBeanIndex(IERC20[] memory tokens) internal view returns (\n        uint[] memory ratios,\n        uint beanIndex,\n        bool success\n    ) {\n        return getRatiosAndBeanIndex(tokens, 0);\n    }\n\n    /**\n     * @dev Returns the price ratios between `tokens` and the index of Bean in `tokens`.\n     * These actions are combined into a single function for gas efficiency.\n     */\n    function getRatiosAndBeanIndex(IERC20[] memory tokens, uint256 lookback) internal view returns (\n        uint[] memory ratios,\n        uint beanIndex,\n        bool success\n    ) {\n        success = true;\n        ratios = new uint[](tokens.length);\n        beanIndex = type(uint256).max;\n        for (uint i; i < tokens.length; ++i) {\n            if (C.BEAN == address(tokens[i])) {\n                beanIndex = i;\n                ratios[i] = 1e6;\n            } else {\n                ratios[i] = LibUsdOracle.getUsdPrice(address(tokens[i]), lookback);\n                if (ratios[i] == 0) {\n                    success = false;\n                }\n            }\n        }\n        require(beanIndex != type(uint256).max, \"Bean not in Well.\");\n    }\n\n    /**\n     * @dev Returns the index of Bean in a list of tokens.\n     */\n    function getBeanIndex(IERC20[] memory tokens) internal pure returns (uint beanIndex) {\n        for (beanIndex; beanIndex < tokens.length; ++beanIndex) {\n            if (C.BEAN == address(tokens[beanIndex])) {\n                return beanIndex;\n            }\n        }\n        revert(\"Bean not in Well.\");\n    }\n\n    /**\n     * @dev Returns the index of Bean given a Well.\n     */\n    function getBeanIndexFromWell(address well) internal view returns (uint beanIndex) {\n        IERC20[] memory tokens = IWell(well).tokens();\n        beanIndex = getBeanIndex(tokens);\n    }\n\n    /**\n     * @dev Returns the non-Bean token within a Well.\n     * Assumes a well with 2 tokens only, with Bean being one of them.\n     * Cannot fail (and thus revert), as wells cannot have 2 of the same tokens as the pairing.\n     */\n    function getNonBeanTokenAndIndexFromWell(\n        address well\n    ) internal view returns (address, uint256) {\n        IERC20[] memory tokens = IWell(well).tokens();\n        for (uint256 i; i < tokens.length; i++) {\n            if (address(tokens[i]) != C.BEAN) {\n                return (address(tokens[i]), i);\n            }\n        }\n    }\n\n    /**\n     * @dev Returns whether an address is a whitelisted Well by checking\n     * if the BDV function selector is the `wellBdv` function.\n     */\n    function isWell(address well) internal view returns (bool _isWell) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        return s.ss[well].selector == WELL_BDV_SELECTOR;\n    }\n\n    /**\n     * @notice gets the non-bean usd liquidity of a well,\n     * using the twa reserves and price in storage.\n     *\n     * @dev this is done for gas efficency purposes, rather than calling the pump multiple times.\n     * This function should be called after the reserves for the well have been set.\n     * Currently this is only done in {seasonFacet.sunrise}.\n     *\n     * if LibWell.getUsdTokenPriceForWell() returns 1, then this function is called without the reserves being set.\n     * if s.usdTokenPrice[well] or s.twaReserves[well] returns 0, then the oracle failed to compute\n     * a valid price this Season, and thus beanstalk cannot calculate the usd liquidity.\n     */\n    function getWellTwaUsdLiquidityFromReserves(\n        address well,\n        uint256[] memory twaReserves\n    ) internal view returns (uint256 usdLiquidity) {\n        uint256 tokenUsd = getUsdTokenPriceForWell(well);\n        (address token, uint256 j) = getNonBeanTokenAndIndexFromWell(well);\n        if (tokenUsd > 1) {\n            return twaReserves[j].mul(1e18).div(tokenUsd);\n        }\n\n        // if tokenUsd == 0, then the beanstalk could not compute a valid eth price,\n        // and should return 0. if s.twaReserves[C.BEAN_ETH_WELL].reserve1 is 0, the previous if block will return 0.\n        if (tokenUsd == 0) {\n            return 0;\n        }\n\n        // if the function reaches here, then this is called outside the sunrise function\n        // (i.e, seasonGetterFacet.getLiquidityToSupplyRatio()).We use LibUsdOracle\n        // to get the price. This should never be reached during sunrise and thus\n        // should not impact gas.\n        return LibUsdOracle.getTokenPrice(token).mul(twaReserves[j]).div(1e6);\n    }\n\n    /**\n     * @dev Sets the price in {AppStorage.usdTokenPrice} given a set of ratios.\n     * It assumes that the ratios correspond to the Constant Product Well indexes.\n     */\n    function setUsdTokenPriceForWell(address well, uint256[] memory ratios) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n\n        // If the reserves length is 0, then {LibWellMinting} failed to compute\n        // valid manipulation resistant reserves and thus the price is set to 0\n        // indicating that the oracle failed to compute a valid price this Season.\n        if (ratios.length == 0) {\n            s.usdTokenPrice[well] = 0;\n        } else {\n            (, uint256 j) = getNonBeanTokenAndIndexFromWell(well);\n            s.usdTokenPrice[well] = ratios[j];\n        }\n    }\n\n    /**\n     * @notice Returns the USD / TKN price stored in {AppStorage.usdTokenPrice}.\n     * @dev assumes TKN has 18 decimals.\n     */\n    function getUsdTokenPriceForWell(address well) internal view returns (uint tokenUsd) {\n        tokenUsd = LibAppStorage.diamondStorage().usdTokenPrice[well];\n    }\n\n    /**\n     * @notice resets token price for a well to 1.\n     * @dev must be called at the end of sunrise() once the\n     * price is not needed anymore to save gas.\n     */\n    function resetUsdTokenPriceForWell(address well) internal {\n        LibAppStorage.diamondStorage().usdTokenPrice[well] = 1;\n    }\n\n    /**\n     * @dev Sets the twaReserves in {AppStorage.usdTokenPrice}.\n     * assumes the twaReserve indexes correspond to the Constant Product Well indexes.\n     * if the length of the twaReserves is 0, then the minting oracle is off.\n     *\n     */\n    function setTwaReservesForWell(address well, uint256[] memory twaReserves) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        // if the length of twaReserves is 0, then return 0.\n        // the length of twaReserves should never be 1, but\n        // is added to prevent revert.\n        if (twaReserves.length <= 1) {\n            delete s.twaReserves[well].reserve0;\n            delete s.twaReserves[well].reserve1;\n        } else {\n            // safeCast not needed as the reserves are uint128 in the wells.\n            s.twaReserves[well].reserve0 = uint128(twaReserves[0]);\n            s.twaReserves[well].reserve1 = uint128(twaReserves[1]);\n        }\n    }\n\n    /**\n     * @notice Returns the TKN / USD price stored in {AppStorage.usdTokenPrice}.\n     * @dev assumes TKN has 18 decimals.\n     */\n    function getTwaReservesForWell(\n        address well\n    ) internal view returns (uint256[] memory twaReserves) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        twaReserves = new uint256[](2);\n        twaReserves[0] = s.twaReserves[well].reserve0;\n        twaReserves[1] = s.twaReserves[well].reserve1;\n    }\n\n    /**\n     * @notice resets token price for a well to 1.\n     * @dev must be called at the end of sunrise() once the\n     * price is not needed anymore to save gas.\n     */\n    function resetTwaReservesForWell(address well) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        s.twaReserves[well].reserve0 = 1;\n        s.twaReserves[well].reserve1 = 1;\n    }\n\n    /**\n     * @notice returns the price in terms of TKN/BEAN. \n     * (if eth is 1000 beans, this function will return 1000e6);\n     */\n    function getBeanTokenPriceFromTwaReserves(address well) internal view returns (uint256 price) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        // s.twaReserve[well] should be set prior to this function being called.\n        if (s.twaReserves[well].reserve0 == 0 || s.twaReserves[well].reserve1 == 0) {\n            price = 0;\n        } else {\n            // fetch the bean index from the well in order to properly return the bean price.\n            if (getBeanIndexFromWell(well) == 0) { \n                price = uint256(s.twaReserves[well].reserve0).mul(1e18).div(s.twaReserves[well].reserve1);\n            } else { \n                price = uint256(s.twaReserves[well].reserve1).mul(1e18).div(s.twaReserves[well].reserve0);\n            }\n        }\n    }\n\n    function getTwaReservesFromStorageOrBeanstalkPump(\n        address well\n    ) internal view returns (uint256[] memory twaReserves) {\n        twaReserves = getTwaReservesForWell(well);\n        if (twaReserves[0] == 1) {\n            twaReserves = getTwaReservesFromBeanstalkPump(well);\n        }\n    }\n\n    /**\n     * @notice gets the TwaReserves of a given well.\n     * @dev only supports wells that are whitelisted in beanstalk.\n     * the initial timestamp and reserves is the timestamp of the start\n     * of the last season. wrapped in try/catch to return gracefully.\n     */\n    function getTwaReservesFromBeanstalkPump(\n        address well\n    ) internal view returns (uint256[] memory) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        try ICumulativePump(C.BEANSTALK_PUMP).readTwaReserves(\n            well,\n            s.wellOracleSnapshots[well],\n            uint40(s.season.timestamp),\n            C.BYTES_ZERO\n        ) returns (uint[] memory twaReserves, bytes memory) {\n            return twaReserves;\n        } catch {\n            return (new uint256[](2));\n        }\n    }\n\n    /**\n     * @notice gets the TwaLiquidity of a given well.\n     * @dev only supports wells that are whitelisted in beanstalk.\n     * the initial timestamp and reserves is the timestamp of the start\n     * of the last season.\n     */\n    function getTwaLiquidityFromBeanstalkPump(\n        address well,\n        uint256 tokenUsdPrice\n    ) internal view returns (uint256 usdLiquidity) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        (, uint256 j) = getNonBeanTokenAndIndexFromWell(well);\n        try ICumulativePump(C.BEANSTALK_PUMP).readTwaReserves(\n            well,\n            s.wellOracleSnapshots[well],\n            uint40(s.season.timestamp),\n            C.BYTES_ZERO\n        ) returns (uint[] memory twaReserves, bytes memory) {\n            usdLiquidity = tokenUsdPrice.mul(twaReserves[j]).div(1e6);\n        } catch {\n            // if pump fails to return a value, return 0.\n            usdLiquidity = 0;\n        }\n    }\n}\n"
      },
      "contracts/libraries/Well/LibWellBdv.sol": {
        "content": "/*\n SPDX-License-Identifier: MIT\n*/\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {IInstantaneousPump} from \"contracts/interfaces/basin/pumps/IInstantaneousPump.sol\";\nimport {Call, IWell} from \"contracts/interfaces/basin/IWell.sol\";\nimport {IWellFunction} from \"contracts/interfaces/basin/IWellFunction.sol\";\nimport {LibWell} from \"contracts/libraries/Well/LibWell.sol\";\nimport {C} from \"contracts/C.sol\";\n\n/**\n * @title Well Bdv Library\n * @notice contains a function to calulate the BDV of a given Well LP Token\n **/\nlibrary LibWellBdv {\n    using SafeMath for uint256;\n\n    uint constant private BEAN_UNIT = 1e6;\n\n    /**\n     * @dev Calculates the `_bdv` of a given Well LP Token given a relevant\n     * `well` and `amount` value by computing the delta LP token supply given a small change in the Bean reserve balance.\n     */\n    function bdv(\n        address well,\n        uint amount\n    ) internal view returns (uint _bdv) {\n        uint beanIndex = LibWell.getBeanIndexFromWell(well);\n\n        // For now, assume all Wells use the default Beanstalk Pump. This should be changed if/when a new Beanstalk Pump is deployed.\n        uint[] memory reserves = IInstantaneousPump(C.BEANSTALK_PUMP).readInstantaneousReserves(well, C.BYTES_ZERO);\n        // If the Bean reserve is beneath the minimum balance, the oracle should be considered as off.\n        require(reserves[beanIndex] >= C.WELL_MINIMUM_BEAN_BALANCE, \"Silo: Well Bean balance below min\");\n        Call memory wellFunction = IWell(well).wellFunction();\n        uint lpTokenSupplyBefore = IWellFunction(wellFunction.target).calcLpTokenSupply(reserves, wellFunction.data);\n        reserves[beanIndex] = reserves[beanIndex].sub(BEAN_UNIT); // remove one Bean\n        uint deltaLPTokenSupply = lpTokenSupplyBefore.sub(\n            IWellFunction(wellFunction.target).calcLpTokenSupply(reserves, wellFunction.data)\n        );\n        _bdv = amount.mul(BEAN_UNIT).div(deltaLPTokenSupply);\n    }\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 100
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}