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/ERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../../utils/Context.sol\";\nimport \"./IERC20.sol\";\nimport \"../../math/SafeMath.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20 {\n    using SafeMath for uint256;\n\n    mapping (address => uint256) private _balances;\n\n    mapping (address => mapping (address => uint256)) private _allowances;\n\n    uint256 private _totalSupply;\n\n    string private _name;\n    string private _symbol;\n    uint8 private _decimals;\n\n    /**\n     * @dev Sets the values for {name} and {symbol}, initializes {decimals} with\n     * a default value of 18.\n     *\n     * To select a different value for {decimals}, use {_setupDecimals}.\n     *\n     * All three of these values are immutable: they can only be set once during\n     * construction.\n     */\n    constructor (string memory name_, string memory symbol_) public {\n        _name = name_;\n        _symbol = symbol_;\n        _decimals = 18;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view virtual returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5,05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is\n     * called.\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view virtual returns (uint8) {\n        return _decimals;\n    }\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view virtual override returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view virtual override returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `recipient` cannot be the zero address.\n     * - the caller must have a balance of at least `amount`.\n     */\n    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(_msgSender(), recipient, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual override returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function approve(address spender, uint256 amount) public virtual override returns (bool) {\n        _approve(_msgSender(), spender, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Emits an {Approval} event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of {ERC20}.\n     *\n     * Requirements:\n     *\n     * - `sender` and `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `amount`.\n     * - the caller must have allowance for ``sender``'s tokens of at least\n     * `amount`.\n     */\n    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(sender, recipient, amount);\n        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n        return true;\n    }\n\n    /**\n     * @dev Atomically increases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n        return true;\n    }\n\n    /**\n     * @dev Atomically decreases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `spender` must have allowance for the caller of at least\n     * `subtractedValue`.\n     */\n    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n        return true;\n    }\n\n    /**\n     * @dev Moves tokens `amount` from `sender` to `recipient`.\n     *\n     * This is internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * Requirements:\n     *\n     * - `sender` cannot be the zero address.\n     * - `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `amount`.\n     */\n    function _transfer(address sender, address recipient, uint256 amount) internal virtual {\n        require(sender != address(0), \"ERC20: transfer from the zero address\");\n        require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n        _beforeTokenTransfer(sender, recipient, amount);\n\n        _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n        _balances[recipient] = _balances[recipient].add(amount);\n        emit Transfer(sender, recipient, amount);\n    }\n\n    /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n     * the total supply.\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     */\n    function _mint(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: mint to the zero address\");\n\n        _beforeTokenTransfer(address(0), account, amount);\n\n        _totalSupply = _totalSupply.add(amount);\n        _balances[account] = _balances[account].add(amount);\n        emit Transfer(address(0), account, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, reducing the\n     * total supply.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     * - `account` must have at least `amount` tokens.\n     */\n    function _burn(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: burn from the zero address\");\n\n        _beforeTokenTransfer(account, address(0), amount);\n\n        _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n        _totalSupply = _totalSupply.sub(amount);\n        emit Transfer(account, address(0), amount);\n    }\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n     *\n     * This internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     */\n    function _approve(address owner, address spender, uint256 amount) internal virtual {\n        require(owner != address(0), \"ERC20: approve from the zero address\");\n        require(spender != address(0), \"ERC20: approve to the zero address\");\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /**\n     * @dev Sets {decimals} to a value other than the default one of 18.\n     *\n     * WARNING: This function should only be called from the constructor. Most\n     * applications that interact with token contracts will not expect\n     * {decimals} to ever change, and may work incorrectly if it does.\n     */\n    function _setupDecimals(uint8 decimals_) internal virtual {\n        _decimals = decimals_;\n    }\n\n    /**\n     * @dev Hook that is called before any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n     * will be to transferred to `to`.\n     * - when `from` is zero, `amount` tokens will be minted for `to`.\n     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }\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/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address payable) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes memory) {\n        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n        return msg.data;\n    }\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"
      },
      "@openzeppelin/contracts/utils/SafeCast.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\n\n    /**\n     * @dev Returns the downcasted uint128 from uint256, reverting on\n     * overflow (when the input is greater than largest uint128).\n     *\n     * Counterpart to Solidity's `uint128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        require(value < 2**128, \"SafeCast: value doesn\\'t fit in 128 bits\");\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint64 from uint256, reverting on\n     * overflow (when the input is greater than largest uint64).\n     *\n     * Counterpart to Solidity's `uint64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        require(value < 2**64, \"SafeCast: value doesn\\'t fit in 64 bits\");\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint32 from uint256, reverting on\n     * overflow (when the input is greater than largest uint32).\n     *\n     * Counterpart to Solidity's `uint32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        require(value < 2**32, \"SafeCast: value doesn\\'t fit in 32 bits\");\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint16 from uint256, reverting on\n     * overflow (when the input is greater than largest uint16).\n     *\n     * Counterpart to Solidity's `uint16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        require(value < 2**16, \"SafeCast: value doesn\\'t fit in 16 bits\");\n        return uint16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint8 from uint256, reverting on\n     * overflow (when the input is greater than largest uint8).\n     *\n     * Counterpart to Solidity's `uint8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits.\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        require(value < 2**8, \"SafeCast: value doesn\\'t fit in 8 bits\");\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        require(value >= 0, \"SafeCast: value must be positive\");\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt128(int256 value) internal pure returns (int128) {\n        require(value >= -2**127 && value < 2**127, \"SafeCast: value doesn\\'t fit in 128 bits\");\n        return int128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt64(int256 value) internal pure returns (int64) {\n        require(value >= -2**63 && value < 2**63, \"SafeCast: value doesn\\'t fit in 64 bits\");\n        return int64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt32(int256 value) internal pure returns (int32) {\n        require(value >= -2**31 && value < 2**31, \"SafeCast: value doesn\\'t fit in 32 bits\");\n        return int32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt16(int256 value) internal pure returns (int16) {\n        require(value >= -2**15 && value < 2**15, \"SafeCast: value doesn\\'t fit in 16 bits\");\n        return int16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits.\n     *\n     * _Available since v3.1._\n     */\n    function toInt8(int256 value) internal pure returns (int8) {\n        require(value >= -2**7 && value < 2**7, \"SafeCast: value doesn\\'t fit in 8 bits\");\n        return int8(value);\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        require(value < 2**255, \"SafeCast: value doesn't fit in an int256\");\n        return int256(value);\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/metadata/MetadataFacet.sol": {
        "content": "/*\n * SPDX-License-Identifier: MIT\n */\n\npragma solidity ^0.7.6;\npragma experimental ABIEncoderV2;\n\nimport \"./MetadataImage.sol\";\nimport {LibBytes} from \"contracts/libraries/LibBytes.sol\";\nimport {LibTokenSilo} from \"contracts/libraries/Silo/LibTokenSilo.sol\";\n\n\n/**\n * @title MetadataFacet\n * @author Brean\n * @notice MetadataFacet is a contract that provides metadata for beanstalk ERC1155 deposits, \n * as well as other auxiliary functions related to ERC1155 deposits.\n * \n * @dev Deposits are represented by a uint256, which is the concatination of the token address and the stem.\n */\ncontract MetadataFacet is MetadataImage {\n    using LibStrings for uint256;\n    using LibStrings for int256;\n\n    event URI(string _uri, uint256 indexed _id);\n\n    /**\n     * @notice Returns the URI for a given depositId.\n     * @param depositId - the id of the deposit\n     * @dev the URI is a base64 encoded JSON object that contains the metadata and base64 encoded svg.\n     * Deposits are stored as a mapping of a uint256 to a Deposit struct.\n     * ERC20 deposits are represented by the concatination of the token address and the stem. (20 + 12 bytes).\n     */\n    function uri(uint256 depositId) external view returns (string memory) {\n        (address token, int96 stem) = LibBytes.unpackAddressAndStem(depositId);\n        int96 stemTip = LibTokenSilo.stemTipForToken(token);\n        // validate the uri\n        // the deposit id must return \n        // 1) a token in the silo whitelist (by checking milestone season)\n        // 2) a stem that is less than or equal to the stem tip\n        require(s.ss[token].milestoneSeason != 0 && stemTip >= stem, \"Silo: metadata does not exist\");\n        bytes memory attributes = abi.encodePacked(\n            ', \"attributes\": [ { \"trait_type\": \"Token\", \"value\": \"', getTokenName(token),\n            '\"}, { \"trait_type\": \"Token Address\", \"value\": \"', LibStrings.toHexString(uint256(token), 20),\n            '\"}, { \"trait_type\": \"Id\", \"value\": \"', depositId.toHexString(32),\n            '\"}, { \"trait_type\": \"stem\", \"display_type\": \"number\", \"value\": ', int256(stem).toString(),\n            '}, { \"trait_type\": \"initial stalk per BDV\", \"display_type\": \"number\", \"value\": ', uint256(LibTokenSilo.stalkIssuedPerBdv(token)).toString(),\n            '}, { \"trait_type\": \"grown stalk per BDV\", \"display_type\": \"number\", \"value\": ', uint256(stemTip - stem).toString(),\n            '}, { \"trait_type\": \"stalk grown per BDV per season\", \"display_type\": \"number\", \"value\": ', uint256(LibTokenSilo.stalkEarnedPerSeason(token)).toString()\n        );\n        return string(abi.encodePacked(\"data:application/json;base64,\",LibBytes64.encode(abi.encodePacked(\n                '{',\n                    '\"name\": \"Beanstalk Silo Deposits\", \"description\": \"An ERC1155 representing an asset deposited in the Beanstalk Silo. Silo Deposits gain stalk and bean seignorage. ',\n                    '\\\\n\\\\nDISCLAIMER: Due diligence is imperative when assessing this NFT. Opensea and other NFT marketplaces cache the svg output and thus, may require the user to refresh the metadata to properly show the correct values.\"',                    \n                    attributes,\n                    string(abi.encodePacked(' }], \"image\": \"', imageURI(token, stem, stemTip), '\"')),\n                '}'\n            ))\n        ));\n    }\n\n    function name() external pure returns (string memory){\n        return \"Beanstalk Silo Deposits\";\n    }\n\n    function symbol() external pure returns (string memory){\n        return \"DEPOSIT\";\n    }\n}\n"
      },
      "contracts/beanstalk/metadata/MetadataImage.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.6;\nimport \"../AppStorage.sol\";\nimport {LibBytes64} from \"contracts/libraries/LibBytes64.sol\";\nimport {LibStrings} from \"contracts/libraries/LibStrings.sol\";\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {C} from \"../../C.sol\";\n\n\n/**\n * @title MetadataImage\n * @author Brean\n * @notice Contains image metadata for ERC1155 deposits.\n * @dev fully on-chain generated SVG.\n */\n\ncontract MetadataImage {\n    AppStorage internal s;\n\n    using LibStrings for uint256;\n    using LibStrings for int256;\n    using SafeMath for uint256;\n\n    string constant LEAF_COLOR_0 = '#A8C83A';\n    string constant LEAF_COLOR_1 = '#89A62F';\n    uint256 constant NUM_PLOTS = 21;\n    uint256 constant STALK_GROWTH = 2e8;\n\n    function imageURI(address token, int96 stem, int96 stemTip) public view returns (string memory) {\n        return string(\n            abi.encodePacked(\n                \"data:image/svg+xml;base64,\", \n                LibBytes64.encode(bytes(generateImage(token, stem, stemTip)))\n            )\n        );\n    }\n\n    function generateImage(address token, int96 stem, int96 stemTip) internal view returns (string memory) {\n        int96 grownStalkPerBdv = stemTip - stem;\n        return string(\n            abi.encodePacked(\n                '<svg class=\"svgBody\" width=\"255\" height=\"350\" viewBox=\"0 0 255 350\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">',\n                defs(grownStalkPerBdv),\n                back(),\n                printPlots(grownStalkPerBdv),\n                blackBars(token, stem),\n                '</svg>'\n            )\n        );\n    }\n\n    function back() internal pure returns(string memory) {\n        return string(abi.encodePacked(\n            '<rect width=\"255\" height=\"350\" rx=\"10\" fill=\"',\n            '#253326',\n            '\"/>'\n        ));\n    }\n\n    function defs(int96 stemTip) internal pure returns(string memory) {\n        (uint256 sprouts,) = getNumStemsAndPlots(stemTip);\n        uint256 sproutsInFinalRow = sprouts.mod(4);\n        return string(abi.encodePacked(\n            '<defs>',\n            plot(),\n            fullLeafPlot(),\n            emptyPlot(),\n            partialLeafRow(sproutsInFinalRow),\n            partialLeafPlot(stemTip),\n            leaf(),\n            silo(),\n            fullLeafRow(),\n            '</defs>'\n        ));\n    }\n\n    function mask() internal pure returns (string memory) {\n        return string(abi.encodePacked(\n            '<clipPath id=\"borderMask\">',\n            border(),\n            '</clipPath>'\n        ));\n    }\n\n    function border() internal pure returns (string memory) {\n        return '<rect x=\"8\" y=\"8\" width=\"240\" height=\"335\" rx=\"6\" stroke=\"#9BCAA0\" stroke-width=\"2\" fill=\"none\"/>';\n    }\n\n    function fullLeafRow() internal pure returns (string memory) {\n        return string(abi.encodePacked(\n            '<g id=\"leafRow\">',\n            '<use xlink:href=\"#leaf\" x=\"0\" y=\"0\"/>',\n            '<use xlink:href=\"#leaf\" x=\"-12\" y=\"-7\"/>',\n            '<use xlink:href=\"#leaf\" x=\"-24\" y=\"-14\"/>',\n            '<use xlink:href=\"#leaf\" x=\"-36\" y=\"-21\"/>',\n            '</g>'\n        ));\n    }\n\n    function partialLeafRow(uint256 n) internal pure returns (string memory) {\n        if (n == 0) { \n            return string(abi.encodePacked(\n                '<g id=\"partialLeafRow\">',\n                '</g>'\n            ));\n        }\n        if (n == 1) { \n            return string(abi.encodePacked(\n                '<g id=\"partialLeafRow\">',\n                '<use xlink:href=\"#leaf\" x=\"0\" y=\"0\"/>',\n                '</g>'\n            ));\n        }\n        if (n == 2) { \n            return string(abi.encodePacked(\n                '<g id=\"partialLeafRow\">',\n                '<use xlink:href=\"#leaf\" x=\"0\" y=\"0\"/>',\n                '<use xlink:href=\"#leaf\" x=\"-12\" y=\"-7\"/>',\n                '</g>'\n            ));\n        }\n        if (n == 3) { \n            return string(abi.encodePacked(\n                '<g id=\"partialLeafRow\">',\n                '<use xlink:href=\"#leaf\" x=\"0\" y=\"0\"/>',\n                '<use xlink:href=\"#leaf\" x=\"-12\" y=\"-7\"/>',\n                '<use xlink:href=\"#leaf\" x=\"-24\" y=\"-14\"/>',\n                '</g>'\n            ));\n        } else {\n            return string(abi.encodePacked(\n                '<g id=\"partialLeafRow\">',\n                '<use xlink:href=\"#leaf\" x=\"0\" y=\"0\"/>',\n                '<use xlink:href=\"#leaf\" x=\"-12\" y=\"-7\"/>',\n                '<use xlink:href=\"#leaf\" x=\"-24\" y=\"-14\"/>',\n                '<use xlink:href=\"#leaf\" x=\"-36\" y=\"-21\"/>',\n                '</g>'\n            ));\n        }\n       \n    }\n\n\n    function fullLeafPlot() internal pure returns (string memory) {\n        return string(abi.encodePacked(\n            '<g id=\"fullLeafPlot\">',\n            useAssetTransform('plot',-35,0),\n            useAssetTransformFill('leafRow',-35,0, LEAF_COLOR_0),\n            useAssetTransformFill('leafRow',-47,7, LEAF_COLOR_1),\n            useAssetTransformFill('leafRow',-60,14, LEAF_COLOR_0),\n            useAssetTransformFill('leafRow',-73,21, LEAF_COLOR_1),\n            '</g>'\n        ));\n    }\n\n    function emptyPlot() internal pure returns (string memory) {\n        return string(abi.encodePacked(\n            '<g id=\"emptyPlot\">',\n            useAssetTransform('plot',-35,0),\n            '</g>'\n        ));\n    }\n\n    function partialLeafPlot(int96 stalkPerBDV) internal pure returns (string memory _plot) {\n        uint256 totalSprouts = uint256(stalkPerBDV).div(STALK_GROWTH).add(16);\n        uint256 numRows = uint256(totalSprouts).div(4).mod(4);\n        uint256 numSprouts = uint256(totalSprouts).mod(4);\n        if (numRows == 0) {\n            if (numSprouts > 0) {\n                _plot = string(abi.encodePacked(\n                    '<g id=\"partialLeafPlot\">',\n                    useAssetTransform('plot',-35,0),\n                    useAssetTransformFill('partialLeafRow',-35,0, LEAF_COLOR_0),\n                    '</g>'\n                ));\n            } else {\n                _plot = string(abi.encodePacked(\n                    '<g id=\"partialLeafPlot\">',\n                    threeLeafRows(),\n                    useAssetTransformFill('leafRow',-73,21, LEAF_COLOR_1),\n                    '</g>'\n                ));\n            }\n        }\n        if (numRows == 1) {\n            if (numSprouts > 0) {\n                _plot = string(abi.encodePacked(\n                    '<g id=\"partialLeafPlot\">',\n                    oneLeafRow(),\n                    useAssetTransformFill('partialLeafRow',-47,7, LEAF_COLOR_1),\n                    '</g>'\n                ));\n            } else {\n                _plot = string(abi.encodePacked(\n                    '<g id=\"partialLeafPlot\">',\n                    oneLeafRow(),\n                    '</g>'\n                ));\n            }\n        }\n        if (numRows == 2) {\n            if (numSprouts > 0) {\n                _plot = string(abi.encodePacked(\n                    '<g id=\"partialLeafPlot\">',\n                    twoLeafRows(),\n                    useAssetTransformFill('partialLeafRow',-60,14, LEAF_COLOR_0),\n                    '</g>'\n                ));\n            } else {\n                _plot = string(abi.encodePacked(\n                    '<g id=\"partialLeafPlot\">',\n                    twoLeafRows(),\n                    '</g>'\n                ));\n            }\n            \n        }\n        if (numRows == 3) {\n            if (numSprouts > 0) {\n                _plot = string(abi.encodePacked(\n                    '<g id=\"partialLeafPlot\">',\n                    threeLeafRows(),\n                    useAssetTransformFill('partialLeafRow',-73,21, LEAF_COLOR_1),\n                    '</g>'\n                ));\n\n            } else {\n                _plot = string(abi.encodePacked(\n                    '<g id=\"partialLeafPlot\">',\n                    threeLeafRows(),\n                    '</g>'\n                ));\n            }\n        }\n    }\n\n    function printPlots(int96 stalkPerBDV) internal pure returns (string memory) {\n        return string(abi.encodePacked(\n            '<use xlink:href=\"#silo\" x=\"99\" y=\"55\"/><g id=\"allPlot\" clip-path=\"url(#borderMask)\">',\n                plotLogic(stalkPerBDV),\n            '</g>'\n        ));\n    }\n\n    function plotLogic(int96 stalkPerBDV) internal pure returns (string memory) {\n\n        int256[2][21] memory XYPLOT = [\n\n        [int256(-69),-164], // 20\n        [int256(69),-164], // 19\n\n        [int256(0),-124], // 13\n        [int256(138),-124], // 18\n        [int256(-138),-124], // 21\n\n        [int256(-69),-84], // 14\n        [int256(69),-84], // 12\n\n        [int256(-138),-44], // 15\n        [int256(0),-44], // 5\n        [int256(138),-44], // 11\n\n        [int256(-69),-4], // 6\n        [int256(69),-4], // 4\n\n        [int256(-138),36], // 7\n        [int256(138),36], // 3\n\n        [int256(-69),76], // 8 \n        [int256(69),76], // 2\n\n        [int256(-138),116], // 16\n        [int256(0),116], // 1\n        [int256(138),116], // 10\n            \n        [int256(69),156], // 9\n        [int256(-69),156] // 17\n        \n        ];\n        uint256[NUM_PLOTS] memory order = [uint256(20),19,13,18,21,14,12,15,5,11,6,4,7,3,8,2,16,1,10,9,17];\n\n        bytes memory _plot;\n\n        (, uint256 numPlotsToFill) = getNumStemsAndPlots(stalkPerBDV);\n\n        // first plot should always be planted fully, and every 2% stalk adds a sprout to the next plot.\n        for(uint256 i = 0; i < NUM_PLOTS; ++i) {\n            uint256 plotNo = order[i];\n            if (plotNo < numPlotsToFill) {\n                _plot = abi.encodePacked(\n                    _plot,\n                    useAsset(\n                        'fullLeafPlot',\n                        XYPLOT[i][0],\n                        XYPLOT[i][1]\n                    )\n                );\n            } else if (plotNo == numPlotsToFill) {\n                if (numPlotsToFill == 1) {\n                    _plot = abi.encodePacked(\n                    _plot,\n                    useAsset(\n                        'fullLeafPlot',\n                        XYPLOT[i][0],\n                        XYPLOT[i][1]\n                    ));\n                } else {\n                    _plot = abi.encodePacked(\n                    _plot,\n                    useAsset(\n                        'partialLeafPlot',\n                        XYPLOT[i][0],\n                        XYPLOT[i][1]\n                    )\n                );\n                }\n                \n            } else {\n                _plot = abi.encodePacked(\n                    _plot,\n                    useAsset(\n                        'emptyPlot',\n                        XYPLOT[i][0],\n                        XYPLOT[i][1]\n                    )\n                );\n            }\n            if (i == 11) {\n                _plot= abi.encodePacked(\n                    _plot,\n                    '<use xlink:href=\"#silo\" x=\"47\" y=\"55\" transform=\"scale(1.7)\"/>'\n                );\n            }\n        }\n        return string(_plot);\n    }\n\n    function useAsset(string memory assetName, int256 x, int256 y) internal pure returns (string memory) { \n        return string(abi.encodePacked(\n            '<use xlink:href=\"#',\n            assetName,\n            '\" x=\"',\n            intToStr(x),\n            '\" y=\"',\n            intToStr(y),\n            '\" />'\n        ));\n    }\n\n    function useAssetFill(string memory assetName, int256 x, int256 y, string memory color) internal pure returns (string memory) { \n        return string(abi.encodePacked(\n            '<use xlink:href=\"#',\n            assetName,\n            '\" x=\"',\n            intToStr(x),\n            '\" y=\"',\n            intToStr(y),\n            '\" fill=\"',\n            color,\n            '\" />'\n        ));\n    }\n\n    function plot() internal pure returns (string memory) {\n        return string(\n            abi.encodePacked(\n                '<g id=\"plot\">',\n                '<path d=\"M79.5728 129.265L127.469 156.833L175.443 129.245L127.469 101.697L79.5728 129.265Z\" fill=\"#944A27\"/>',\n                '<path d=\"M79.5332 133.426L79.5727 129.265L127.469 156.833L127.507 160.908L79.5332 133.426Z\" fill=\"#75391F\"/>',\n                '<path d=\"M175.467 133.4L175.443 129.245L127.469 156.833L127.507 160.908L175.467 133.4Z\" fill=\"#67331E\"/>',\n                \"</g>\"\n            )\n        );\n    }\n\n    function leaf() internal pure returns (string memory) { \n        return string(\n            abi.encodePacked(\n                '<g id=\"leaf\">',\n                '<path d=\"M171.884 118.983a4.932 4.932 0 0 1-1.018 2.606 4.715 4.715 0 0 1-1.878 1.439c-.465.195-1.735.727-2.364.176-.246 3.298-1.593 6.512-2.253 7.954a4.532 4.532 0 0 1-.313-.933c-.211-.975-.038-1.763.078-2.295.202-.921.353-1.612.467-2.14-1.177.694-2.642.569-3.558-.272-.796-.732-1.083-1.921-.743-3.034.498.011 1.939.109 3.247 1.167a5.13 5.13 0 0 1 1.21 1.413c.159-.74.199-.958.238-1.179.209-1.213.322-1.872.274-2.724a7.73 7.73 0 0 0-.908-3.177c-.772.415-1.789.196-2.378-.304-.339-.287-.556-.682-.764-1.692a12.739 12.739 0 0 1-.176-3.909c.789.603 1.47 1.019 1.937 1.283.944.536 1.344.639 1.761 1.167.152.193.649.842.586 1.751-.011.172-.053.795-.464 1.293a6.83 6.83 0 0 1 1.384 2.227c.14.368.242.744.311 1.15.107-.207.261-.439.511-.722.453-.513.87-.992 1.604-1.284.683-.272 1.28-.249 1.723-.234a5.302 5.302 0 0 1 1.486.273Z\"/>',\n                '</g>'\n            )\n        );\n    }\n\n    function silo() internal pure returns (string memory) {\n        return string(\n            abi.encodePacked(\n                '<g id=\"silo\">',\n                '<path d=\"M57.108 71.29c.188-11.653-12.01-21.303-27.243-21.552-15.234-.25-27.736 8.995-27.923 20.649-.187 11.654 12.01 21.304 27.244 21.553 15.233.25 27.735-8.995 27.922-20.65Z\" fill=\"#666\"/>',\n                '<path d=\"M.464 19.544c.699 16.585 1.4 33.169 2.098 49.752.021 2.381.48 4.278.883 5.539.277.86.741 2.275 1.778 3.867.494.759 1.212 1.7 3.002 3.332 1.739 1.586 3.35 3.056 5.732 4.398 3.293 1.855 6.151 2.396 8.791 2.896 1.855.35 5.149.948 9.488.556a32.707 32.707 0 0 0 9.315-2.287c1.862-.759 4.642-1.917 7.633-4.4 1.348-1.12 3.448-2.897 5.197-5.95a20.114 20.114 0 0 0 2.25-5.998c.21-17.552.42-35.104.632-52.657l-56.8.952h.001Z\" fill=\"#B3B3B3\"/>',\n                '<path d=\"M57.48 19.482C57.645 9.24 44.978.727 29.187.468 13.397.21.463 8.303.298 18.546.134 28.788 12.8 37.3 28.591 37.56c15.79.258 28.724-7.835 28.889-18.078Z\" fill=\"#CCC\"/>',\n                '<path d=\"M30.314 7.137c.009-.561-.68-1.028-1.538-1.042-.859-.014-1.562.43-1.571.991-.01.562.68 1.028 1.538 1.042.859.015 1.562-.43 1.57-.99Z\" fill=\"#666\"/>',\n                '<path d=\"M6.414 28.89a15.777 15.777 0 0 1-2.093-2.146c-.856-1.063-2.453-3.093-2.975-6.112a11.765 11.765 0 0 1-.093-3.307l25.43-9.976c.043.142.188.555.604.868.46.346.947.34 1.086.334L6.413 28.888v.002Z\" fill=\"#E6E6E6\"/>',\n                '<path opacity=\".33\" d=\"M1.477 16.029c.25-.931.706-2.258 1.57-3.695.655-1.092 1.292-1.825 1.76-2.358.584-.665 1.776-1.934 3.679-3.29 2.953-2.105 5.696-3.05 7.723-3.73a37.35 37.35 0 0 1 6.485-1.547l5.242 4.316a1.48 1.48 0 0 0-1.214.967L1.48 16.03h-.002Z\" fill=\"#999\"/>',\n                '<path opacity=\".44\" d=\"M1.81 26.532c.206.494.484 1.05.86 1.63a10.266 10.266 0 0 0 2.278 2.486L6.552 78.22a17.272 17.272 0 0 1-3-7.413L1.81 26.532Z\" fill=\"#E6E6E6\"/>',\n                '<path d=\"m33.092 49.441-6.381 15.211s-6.078-11.159 6.381-15.21Z\" fill=\"#8E8E8E\"/>',\n                '<path d=\"m26.725 64.858-.091-.175c-.026-.049-2.634-4.923-.867-9.37 1.057-2.717 3.518-4.725 7.3-5.946l.187-.061-6.53 15.552Zm6.212-15.268c-3.621 1.217-5.991 3.168-7.022 5.798-1.538 3.908.355 8.166.788 9.054l6.234-14.852ZM28.093 63.737l4.484-10.87s7.365 6.337-4.484 10.87Z\" fill=\"#8E8E8E\"/>'\n                \"</g>\"\n            )\n        );\n    }\n\n    function useAssetTransform(string memory assetName, int256 x, int256 y) internal pure returns (string memory) { \n        return string(abi.encodePacked(\n            '<use xlink:href=\"#',\n            assetName,\n            '\" x=\"',\n            intToStr(x),\n            '\" y=\"',\n            intToStr(y),\n            '\" transform=\"scale(1.4)\"/>'\n        ));\n    }\n\n    function useAssetTransformFill(string memory assetName, int256 x, int256 y, string memory color) internal pure returns (string memory) { \n        return string(abi.encodePacked(\n            '<use xlink:href=\"#',\n            assetName,\n            '\" x=\"',\n            intToStr(x),\n            '\" y=\"',\n            intToStr(y),\n            '\" fill=\"',\n            color,\n            '\" transform=\"scale(1.4)\"/>'\n        ));\n    }\n\n    function threeLeafRows() internal pure returns (string memory) {\n        return string(\n            abi.encodePacked(\n                twoLeafRows(),\n                useAssetTransformFill('leafRow',-60,14, LEAF_COLOR_0)\n            )\n        );\n    }\n\n    function twoLeafRows() internal pure returns (string memory) {\n        return string(\n            abi.encodePacked(\n                oneLeafRow(),\n                useAssetTransformFill('leafRow',-47,7, LEAF_COLOR_1)\n            )\n        );\n    }\n\n    function oneLeafRow() internal pure returns(string memory) {\n        return string(\n            abi.encodePacked(\n                useAssetTransform('plot',-35,0),\n                useAssetTransformFill('leafRow',-35,0, LEAF_COLOR_0)\n            )\n        );\n    }\n\n    function blackBars(address token, int96 stem) internal view returns(string memory) {\n        return string(\n            abi.encodePacked(\n                '<rect x=\"0\" y=\"0\" width=\"255\" height=\"20\" rx=\"5\" fill=\"#242424\"/>',\n                tokenName(token),\n                '<rect x=\"0\" y=\"330\" width=\"255\" height=\"20\" rx=\"5\" fill=\"#242424\"/>',\n                movingTokenAddress(token),\n                '<text x=\"245\" y=\"14.5\" font-size=\"12\" fill=\"White\" text-anchor=\"end\" font-family=\"futura\">Stem: ',\n                sciNotation(stem),\n                '</text>'\n            )\n        );\n    }\n\n    function sciNotation(int96 stem) internal pure returns (string memory) {\n        if (stem >= 0) {\n            // if stem is greater than 1e5, use scientific notation\n            if (stem > 100_000) {\n                return powerOfTen(uint256(stem));\n            } else {\n                return uint256(stem).toString();\n            }\n        } else {\n            // if stem is less than -1e5, use scientific notation\n            if (-stem > 100_000) {\n                return string(abi.encodePacked(\"-\", powerOfTen(uint256(-stem))));\n            } else {\n                return int256(stem).toString();\n            }\n        }\n    }\n\n    function powerOfTen(uint256 stem) internal pure returns (string memory) {\n        // silo v3.1 increased the precision of stems by 1e6. \n        // we truncate the stem by 6 decimal places in order to support a wider range of stems.\n        // the inaccuracy is acceptable given the stem is only used for cosmetic reasons. \n        stem = stem / 1e6;\n        // if else ladder to determine how many digits to show.\n        if (stem < 1e6) {\n            return stemDecimals(stem, 5);\n        } else if (stem < 1e7) {\n            return stemDecimals(stem, 6);\n        } else if (stem < 1e8) {\n            return stemDecimals(stem, 7);\n        } else if (stem < 1e9) {\n            return stemDecimals(stem, 8);\n        } else if (stem < 1e10) {\n            return stemDecimals(stem, 9);\n        } else if (stem < 1e11) {\n            return stemDecimals(stem, 10);\n        } else if (stem < 1e12) {\n            return stemDecimals(stem, 11);\n        } else if (stem < 1e13) {\n            return stemDecimals(stem, 12);\n        } else if (stem < 1e14) {\n            return stemDecimals(stem, 13);\n        } else if (stem < 1e15) {\n            return stemDecimals(stem, 14);\n        } else if (stem < 1e16) {\n            return stemDecimals(stem, 15);\n        } else if (stem < 1e17) {\n            return stemDecimals(stem, 16);\n        } else if (stem < 1e18) {\n            return stemDecimals(stem, 17);\n        } else if (stem < 1e19) {\n            return stemDecimals(stem, 18);\n        } else if (stem < 1e20) {\n            return stemDecimals(stem, 19);\n        } else if (stem < 1e21) {\n            return stemDecimals(stem, 20);\n        } else if (stem < 1e22) {\n            return stemDecimals(stem, 21);\n        } else if (stem < 1e23) {\n            return stemDecimals(stem, 22);\n        } else if (stem < 1e24) {\n            return stemDecimals(stem, 23);\n        } else if (stem < 1e25) {\n            return stemDecimals(stem, 24);\n        } else if (stem < 1e26) {\n            return stemDecimals(stem, 25);\n        } else if (stem < 1e27) {\n            return stemDecimals(stem, 26);\n        } else if (stem < 1e28) {\n            return stemDecimals(stem, 27);\n        } else {\n            return stemDecimals(stem, 28);\n        }\n    }\n    \n    function stemDecimals(uint256 stem, uint256 exponent) internal pure returns (string memory) {\n        return string(abi.encodePacked(\n            stem.div(10 ** exponent).toString(),\n            '.',\n            stem.div(10 ** exponent.sub(5)).mod(1e5).toString(),\n            'e',\n            exponent.toString()\n        ));\n    }\n\n    function tokenName(address token) internal view returns (string memory) {\n        return string(\n            abi.encodePacked(\n                '<text x=\"10\" y=\"14.5\" font-size=\"12\" fill=\"White\" text-anchor=\"start\" font-family=\"futura\">',\n                getTokenName(token),\n                '</text>'\n            )\n        );\n    }\n\n    function movingTokenAddress(address token) internal pure returns (string memory) {\n        return string(\n            abi.encodePacked(\n                '<text x=\"127\" y=\"343\" font-size=\"10\" fill=\"White\" text-anchor=\"middle\" font-family=\"futura\">',\n                '<tspan><animate attributeName=\"x\" from=\"375\" to=\"50\" dur=\"10s\" repeatCount=\"indefinite\" />',\n                LibStrings.toHexString(token),\n                '</tspan></text>',\n                '<text x=\"127\" y=\"343\" font-size=\"10\" fill=\"White\" text-anchor=\"middle\" font-family=\"futura\">',\n                '<tspan><animate attributeName=\"x\" from=\"50\" to=\"-275\" dur=\"10s\" repeatCount=\"indefinite\" />',\n                LibStrings.toHexString(token),\n                '</tspan></text>'\n            )\n        );\n    }\n\n    function intToStr(int256 x) internal pure returns (string memory) {\n        if (x < 0) {\n            return string(abi.encodePacked(\n                '-',\n                uint256(-x).toString()\n            ));\n        } else {\n            return uint256(x).toString();\n        }        \n    }\n\n    \n    function getTokenName(address token) internal view returns (string memory tokenString) {\n        // for unripe LP, return `urLP` given the current unripe name is inaccurate. \n        if (token == C.UNRIPE_LP) {\n            tokenString = \"urBEANLP\";\n        } else {\n            tokenString = ERC20(token).symbol();\n        }\n    }\n\n    function getNumStemsAndPlots(int96 grownStalkPerBDV) \n        internal \n        pure \n        returns (uint256 numStems, uint256 plots)\n    {\n        // 1 sprout on the image is equal to 0.02 stalk\n        numStems = uint256(grownStalkPerBDV).div(STALK_GROWTH);\n        plots = numStems.div(16).add(1);\n        if (numStems.mod(16) > 0) plots = plots.add(1);\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/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/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/LibBytes.sol": {
        "content": "/**\n * SPDX-License-Identifier: MIT\n **/\n \npragma solidity =0.7.6;\n\n/* \n* @author: Malteasy\n* @title: LibBytes\n*/\n\nlibrary LibBytes {\n\n    /*\n    * @notice From Solidity Bytes Arrays Utils\n    * @author Gonçalo Sá <goncalo.sa@consensys.net>\n    */\n    function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {\n        require(_start + 1 >= _start, \"toUint8_overflow\");\n        require(_bytes.length >= _start + 1 , \"toUint8_outOfBounds\");\n        uint8 tempUint;\n\n        assembly {\n            tempUint := mload(add(add(_bytes, 0x1), _start))\n        }\n\n        return tempUint;\n    }\n\n    /*\n    * @notice From Solidity Bytes Arrays Utils\n    * @author Gonçalo Sá <goncalo.sa@consensys.net>\n    */\n    function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {\n        require(_start + 4 >= _start, \"toUint32_overflow\");\n        require(_bytes.length >= _start + 4, \"toUint32_outOfBounds\");\n        uint32 tempUint;\n\n        assembly {\n            tempUint := mload(add(add(_bytes, 0x4), _start))\n        }\n\n        return tempUint;\n    }\n\n    /*\n    * @notice From Solidity Bytes Arrays Utils\n    * @author Gonçalo Sá <goncalo.sa@consensys.net>\n    */\n    function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {\n        require(_start + 32 >= _start, \"toUint256_overflow\");\n        require(_bytes.length >= _start + 32, \"toUint256_outOfBounds\");\n        uint256 tempUint;\n\n        assembly {\n            tempUint := mload(add(add(_bytes, 0x20), _start))\n        }\n\n        return tempUint;\n    }\n\n    /**\n    * @notice Loads a slice of a calldata bytes array into memory\n    * @param b The calldata bytes array to load from\n    * @param start The start of the slice\n    * @param length The length of the slice\n    */\n    function sliceToMemory(bytes calldata b, uint256 start, uint256 length) internal pure returns (bytes memory) {\n        bytes memory memBytes = new bytes(length);\n        for(uint256 i = 0; i < length; ++i) {\n            memBytes[i] = b[start + i];\n        }\n        return memBytes;\n    }\n\n    function packAddressAndStem(address _address, int96 stem) internal pure returns (uint256) {\n        return uint256(_address) << 96 | uint96(stem);\n    }\n\n    function unpackAddressAndStem(uint256 data) internal pure returns(address, int96) {\n        return (address(uint160(data >> 96)), int96(int256(data)));\n    }\n\n\n}"
      },
      "contracts/libraries/LibBytes64.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.7.6;\n\n/**\n * @author Brean\n * @dev Provides a set of functions to operate with Base64 strings.\n * @title Base64 is a 0.7.6 variation of Open Zeppelin's Base64.\n *\n */\nlibrary LibBytes64 {\n    /**\n     * @dev Base64 Encoding/Decoding Table\n     */\n    string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n    /**\n     * @dev Converts a `bytes` to its Bytes64 `string` representation.\n     */\n    function encode(bytes memory data) internal pure returns (string memory) {\n        /**\n         * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n         * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n         */\n        if (data.length == 0) return \"\";\n\n        // Loads the table into memory\n        string memory table = _TABLE;\n\n        // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n        // and split into 4 numbers of 6 bits.\n        // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n        // - `data.length + 2`  -> Round up\n        // - `/ 3`              -> Number of 3-bytes chunks\n        // - `4 *`              -> 4 characters for each chunk\n        string memory result = new string(4 * ((data.length + 2) / 3));\n\n        assembly {\n            // Prepare the lookup table (skip the first \"length\" byte)\n            let tablePtr := add(table, 1)\n\n            // Prepare result pointer, jump over length\n            let resultPtr := add(result, 32)\n\n            // Run over the input, 3 bytes at a time\n            for {\n                let dataPtr := data\n                let endPtr := add(data, mload(data))\n            } lt(dataPtr, endPtr) {\n\n            } {\n                // Advance 3 bytes\n                dataPtr := add(dataPtr, 3)\n                let input := mload(dataPtr)\n\n                // To write each character, shift the 3 bytes (18 bits) chunk\n                // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n                // and apply logical AND with 0x3F which is the number of\n                // the previous character in the ASCII table prior to the Base64 Table\n                // The result is then added to the table to get the character to write,\n                // and finally write it in the result pointer but with a left shift\n                // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n                resultPtr := add(resultPtr, 1) // Advance\n\n                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n                resultPtr := add(resultPtr, 1) // Advance\n\n                mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n                resultPtr := add(resultPtr, 1) // Advance\n\n                mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n                resultPtr := add(resultPtr, 1) // Advance\n            }\n\n            // When data `bytes` is not exactly 3 bytes long\n            // it is padded with `=` characters at the end\n            switch mod(mload(data), 3)\n            case 1 {\n                mstore8(sub(resultPtr, 1), 0x3d)\n                mstore8(sub(resultPtr, 2), 0x3d)\n            }\n            case 2 {\n                mstore8(sub(resultPtr, 1), 0x3d)\n            }\n        }\n\n        return result;\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/LibSafeMath32.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @author Publius\n * @title LibSafeMath32 is a uint32 variation of Open Zeppelin's Safe Math library.\n**/\nlibrary LibSafeMath32 {\n    /**\n     * @dev Returns the addition of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryAdd(uint32 a, uint32 b) internal pure returns (bool, uint32) {\n        uint32 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(uint32 a, uint32 b) internal pure returns (bool, uint32) {\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(uint32 a, uint32 b) internal pure returns (bool, uint32) {\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        uint32 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(uint32 a, uint32 b) internal pure returns (bool, uint32) {\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(uint32 a, uint32 b) internal pure returns (bool, uint32) {\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(uint32 a, uint32 b) internal pure returns (uint32) {\n        uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {\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(uint32 a, uint32 b) internal pure returns (uint32) {\n        if (a == 0) return 0;\n        uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {\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(uint32 a, uint32 b) internal pure returns (uint32) {\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(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) {\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(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) {\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(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) {\n        require(b > 0, errorMessage);\n        return a % b;\n    }\n}\n"
      },
      "contracts/libraries/LibSafeMathSigned128.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @title SignedSafeMath\n * @dev Signed math operations with safety checks that revert on error.\n */\nlibrary LibSafeMathSigned128 {\n    int128 constant private _INT128_MIN = -2**127;\n\n    /**\n     * @dev Returns the multiplication of two signed integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `*` operator.\n     *\n     * Requirements:\n     *\n     * - Multiplication cannot overflow.\n     */\n    function mul(int128 a, int128 b) internal pure returns (int128) {\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) {\n            return 0;\n        }\n\n        require(!(a == -1 && b == _INT128_MIN), \"SignedSafeMath: multiplication overflow\");\n\n        int128 c = a * b;\n        require(c / a == b, \"SignedSafeMath: multiplication overflow\");\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the integer division of two signed integers. Reverts 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(int128 a, int128 b) internal pure returns (int128) {\n        require(b != 0, \"SignedSafeMath: division by zero\");\n        require(!(b == -1 && a == _INT128_MIN), \"SignedSafeMath: division overflow\");\n\n        int128 c = a / b;\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the subtraction of two signed integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     *\n     * - Subtraction cannot overflow.\n     */\n    function sub(int128 a, int128 b) internal pure returns (int128) {\n        int128 c = a - b;\n        require((b >= 0 && c <= a) || (b < 0 && c > a), \"SignedSafeMath: subtraction overflow\");\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the addition of two signed integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `+` operator.\n     *\n     * Requirements:\n     *\n     * - Addition cannot overflow.\n     */\n    function add(int128 a, int128 b) internal pure returns (int128) {\n        int128 c = a + b;\n        require((b >= 0 && c >= a) || (b < 0 && c < a), \"SignedSafeMath: addition overflow\");\n\n        return c;\n    }\n}"
      },
      "contracts/libraries/LibSafeMathSigned96.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @title SignedSafeMath\n * @dev Signed math operations with safety checks that revert on error.\n */\nlibrary LibSafeMathSigned96 {\n    int96 constant private _INT96_MIN = -2**95;\n\n    /**\n     * @dev Returns the multiplication of two signed integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `*` operator.\n     *\n     * Requirements:\n     *\n     * - Multiplication cannot overflow.\n     */\n    function mul(int96 a, int96 b) internal pure returns (int96) {\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) {\n            return 0;\n        }\n\n        require(!(a == -1 && b == _INT96_MIN), \"SignedSafeMath: multiplication overflow\");\n\n        int96 c = a * b;\n        require(c / a == b, \"SignedSafeMath: multiplication overflow\");\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the integer division of two signed integers. Reverts 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(int96 a, int96 b) internal pure returns (int96) {\n        require(b != 0, \"SignedSafeMath: division by zero\");\n        require(!(b == -1 && a == _INT96_MIN), \"SignedSafeMath: division overflow\");\n\n        int96 c = a / b;\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the subtraction of two signed integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     *\n     * - Subtraction cannot overflow.\n     */\n    function sub(int96 a, int96 b) internal pure returns (int96) {\n        int96 c = a - b;\n        require((b >= 0 && c <= a) || (b < 0 && c > a), \"SignedSafeMath: subtraction overflow\");\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the addition of two signed integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `+` operator.\n     *\n     * Requirements:\n     *\n     * - Addition cannot overflow.\n     */\n    function add(int96 a, int96 b) internal pure returns (int96) {\n        int96 c = a + b;\n        require((b >= 0 && c >= a) || (b < 0 && c < a), \"SignedSafeMath: addition overflow\");\n\n        return c;\n    }\n}"
      },
      "contracts/libraries/LibStrings.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary LibStrings {\n\n    bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n    uint8 private constant _ADDRESS_LENGTH = 20;\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        // Inspired by OraclizeAPI's implementation - MIT licence\n        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n        if (value == 0) {\n            return \"0\";\n        }\n        uint256 temp = value;\n        uint256 digits;\n        while (temp != 0) {\n            digits++;\n            temp /= 10;\n        }\n        bytes memory buffer = new bytes(digits);\n        uint256 index = digits - 1;\n        temp = value;\n        while (temp != 0) {\n            buffer[index--] = bytes1(uint8(48 + temp % 10));\n            temp /= 10;\n        }\n        return string(buffer);\n    }\n\n     function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = _SYMBOLS[value & 0xf];\n            value >>= 4;\n        }\n        require(value == 0, \"Strings: hex length insufficient\");\n        return string(buffer);\n    }\n\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n    }\n\n    /**\n     * @dev Converts a `int256` to its ASCII `string` representation.\n     */\n    function toString(int256 value) internal pure returns(string memory){\n        if(value > 0){\n            return toString(uint256(value));\n        } else {\n            return string(abi.encodePacked(\"-\", toString(uint256(-value))));\n        }\n    }\n}\n"
      },
      "contracts/libraries/Silo/LibGerminate.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport {LibAppStorage, Storage, AppStorage, Account} from \"../LibAppStorage.sol\";\nimport {LibSafeMath128} from \"../LibSafeMath128.sol\";\nimport {LibSafeMath32} from \"../LibSafeMath32.sol\";\nimport {LibSafeMathSigned96} from \"../LibSafeMathSigned96.sol\";\nimport {LibTokenSilo} from \"./LibTokenSilo.sol\";\nimport {LibSilo} from \"./LibSilo.sol\";\nimport {SafeCast} from \"@openzeppelin/contracts/utils/SafeCast.sol\";\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {C} from \"../../C.sol\";\n\n/**\n * @title LibGerminate\n * @author Brean\n * @notice LibGerminate handles logic associated with germination.\n * @dev \"germinating\" values are values that are currently inactive.\n * germinating values stay germinating until the 1 + the remainder of the current season as passed,\n * in which case they become active.\n *\n * The following are germinating:\n * - newly issued stalk (from new deposits or mowing)\n * - roots from newly issued stalk\n * - new bdv introduced in the silo.\n */\nlibrary LibGerminate {\n    using SafeMath for uint256;\n    using SafeCast for uint256;\n    using LibSafeMath32 for uint32;\n    using LibSafeMath128 for uint128;\n    using LibSafeMathSigned96 for int96;\n\n    //////////////////////// EVENTS ////////////////////////\n\n    /**\n     * @notice emitted when the farmers germinating stalk changes.\n     */\n    event FarmerGerminatingStalkBalanceChanged(\n        address indexed account,\n        int256 deltaGerminatingStalk,\n        Germinate germinationState\n    );\n\n    /**\n     * @notice emitted when the total germinating amount/bdv changes.\n     * @param germinationSeason the season the germination occured.\n     * Does not always equal the current season.\n     * @param token the token being updated.\n     * @param deltaAmount the change in the total germinating amount.\n     * @param deltaBdv the change in the total germinating bdv.\n     */\n    event TotalGerminatingBalanceChanged(\n        uint256 germinationSeason,\n        address indexed token,\n        int256 deltaAmount,\n        int256 deltaBdv\n    );\n\n    /**\n     * @notice emitted when the total germinating stalk changes.\n     * @param germinationSeason issuance season of germinating stalk\n     * @param deltaGerminatingStalk the change in the total germinating stalk.\n     * @dev the issuance season may differ from the season that this event was emitted in..\n     */\n    event TotalGerminatingStalkChanged(uint256 germinationSeason, int256 deltaGerminatingStalk);\n\n    /**\n     * @notice emitted at the sunrise function when the total stalk and roots are incremented.\n     * @dev currently, stalk and roots can only increase at the end of `endTotalGermination`,\n     * but is casted in the event to allow for future decreases.\n     */\n    event TotalStalkChangedFromGermination(int256 deltaStalk, int256 deltaRoots);\n\n    struct GermStem {\n        int96 germinatingStem;\n        int96 stemTip;\n    }\n    /**\n     * @notice Germinate determines what germination struct to use.\n     * @dev \"odd\" and \"even\" refers to the value of the season counter.\n     * \"Odd\" germinations are used when the season is odd, and vice versa.\n     */\n    enum Germinate {\n        ODD,\n        EVEN,\n        NOT_GERMINATING\n    }\n\n    /**\n     * @notice Ends the germination process of system-wide values.\n     * @dev we calculate the unclaimed germinating roots of 2 seasons ago\n     * as the roots of the stalk should be calculated based on the total stalk\n     * when germination finishes, rather than when germination starts.\n     */\n    function endTotalGermination(uint32 season, address[] memory tokens) external {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n\n        // germination can only occur after season 3.\n        if (season < 2) return;\n        uint32 germinationSeason = season.sub(2);\n\n        // base roots are used if there are no roots in the silo.\n        // root calculation is skipped if no deposits have been made\n        // in the season.\n        uint128 finishedGerminatingStalk = s.unclaimedGerminating[germinationSeason].stalk;\n        uint128 rootsFromGerminatingStalk;\n        if (s.s.roots == 0) {\n            rootsFromGerminatingStalk = finishedGerminatingStalk.mul(uint128(C.getRootsBase()));\n        } else if (s.unclaimedGerminating[germinationSeason].stalk > 0) {\n            rootsFromGerminatingStalk = s.s.roots.mul(finishedGerminatingStalk).div(s.s.stalk).toUint128();\n        }\n        s.unclaimedGerminating[germinationSeason].roots = rootsFromGerminatingStalk;\n        // increment total stalk and roots based on unclaimed values.\n        s.s.stalk = s.s.stalk.add(finishedGerminatingStalk);\n        s.s.roots = s.s.roots.add(rootsFromGerminatingStalk);\n\n        // increment total deposited and amounts for each token.\n        Storage.TotalGerminating storage totalGerm;\n        if (getSeasonGerminationState() == Germinate.ODD) {\n            totalGerm = s.oddGerminating;\n        } else {\n            totalGerm = s.evenGerminating;\n        }\n        for (uint i; i < tokens.length; ++i) {\n            // if the token has no deposits, skip.\n            if (totalGerm.deposited[tokens[i]].amount == 0) {\n                continue;\n            }\n\n            LibTokenSilo.incrementTotalDeposited(\n                tokens[i],\n                totalGerm.deposited[tokens[i]].amount,\n                totalGerm.deposited[tokens[i]].bdv\n            );\n\n            // emit events.\n            emit TotalGerminatingBalanceChanged(\n                germinationSeason,\n                tokens[i],\n                -int256(totalGerm.deposited[tokens[i]].amount),\n                -int256(totalGerm.deposited[tokens[i]].bdv)\n            );\n            // clear deposited values.\n            delete totalGerm.deposited[tokens[i]];\n        }\n\n        // emit change in total germinating stalk.\n        // safecast not needed as finishedGerminatingStalk is initially a uint128.\n        emit TotalGerminatingStalkChanged(germinationSeason, -int256(finishedGerminatingStalk));\n        emit TotalStalkChangedFromGermination(int256(finishedGerminatingStalk), int256(rootsFromGerminatingStalk));\n    }\n\n    /**\n     * @notice contains logic for ending germination for stalk and roots.\n     * @param account address of the account to end germination for.\n     * @param lastMowedSeason the last season the account mowed.\n     *\n     * @dev `first` refers to the set of germinating stalk\n     * and roots created in the season closest to the current season.\n     * i.e if a user deposited in season 10 and 11, the `first` stalk\n     * would be season 11.\n     *\n     * the germination process:\n     * - increments the assoicated values (bdv, stalk, roots)\n     * - clears the germination struct for the account.\n     */\n    function endAccountGermination(\n        address account,\n        uint32 lastMowedSeason,\n        uint32 currentSeason\n    ) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        bool lastUpdateOdd = isSeasonOdd(lastMowedSeason);\n        (uint128 firstStalk, uint128 secondStalk) = getGerminatingStalk(account, lastUpdateOdd);\n        uint128 totalRootsFromGermination;\n        uint128 germinatingStalk;\n\n        // check to end germination for first stalk.\n        // if last mowed season is greater or equal than (currentSeason - 1),\n        // then the first stalk is still germinating.\n        if (firstStalk > 0 && lastMowedSeason < currentSeason.sub(1)) {\n            (uint128 roots, Germinate germState) = claimGerminatingRoots(\n                account,\n                lastMowedSeason,\n                firstStalk,\n                lastUpdateOdd\n            );\n            germinatingStalk = firstStalk;\n            totalRootsFromGermination = roots;\n            emit FarmerGerminatingStalkBalanceChanged(\n                account,\n                -int256(germinatingStalk),\n                germState\n            );\n        }\n\n        // check to end germination for second stalk.\n        if (secondStalk > 0) {\n            (uint128 roots, Germinate germState) = claimGerminatingRoots(\n                account,\n                lastMowedSeason.sub(1),\n                secondStalk,\n                !lastUpdateOdd\n            );\n            germinatingStalk = germinatingStalk.add(secondStalk);\n            totalRootsFromGermination = totalRootsFromGermination.add(roots);\n            emit FarmerGerminatingStalkBalanceChanged(account, -int256(germinatingStalk), germState);\n        }\n\n        // increment users stalk and roots.\n        if (germinatingStalk > 0) {\n            s.a[account].s.stalk = s.a[account].s.stalk.add(germinatingStalk);\n            s.a[account].roots = s.a[account].roots.add(totalRootsFromGermination);\n\n            // emit event. Active stalk is incremented, germinating stalk is decremented.\n            emit LibSilo.StalkBalanceChanged(\n                account,\n                int256(germinatingStalk),\n                int256(totalRootsFromGermination)\n            );\n        }\n    }\n\n    /**\n     * @notice Claims the germinating roots of an account,\n     * as well as clears the germinating stalk and roots.\n     *\n     * @param account address of the account to end germination for.\n     * @param season the season to calculate the germinating roots for.\n     * @param stalk the stalk to calculate the germinating roots for.\n     * @param clearOdd whether to clear the odd or even germinating stalk.\n     */\n    function claimGerminatingRoots(\n        address account,\n        uint32 season,\n        uint128 stalk,\n        bool clearOdd\n    ) private returns (uint128 roots, Germinate germState) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n\n        roots = calculateGerminatingRoots(season, stalk);\n\n        if (clearOdd) {\n            delete s.a[account].farmerGerminating.odd;\n            germState = Germinate.ODD;\n        } else {\n            delete s.a[account].farmerGerminating.even;\n            germState = Germinate.EVEN;\n        }\n\n        // deduct from unclaimed values.\n        s.unclaimedGerminating[season].stalk = s.unclaimedGerminating[season].stalk.sub(stalk);\n        s.unclaimedGerminating[season].roots = s.unclaimedGerminating[season].roots.sub(roots);\n    }\n\n    /**\n     * @notice calculates the germinating roots for a given stalk and season.\n     * @param season the season to use when calculating the germinating roots.\n     * @param stalk the stalk to calculate the germinating roots for.\n     */\n    function calculateGerminatingRoots(\n        uint32 season,\n        uint128 stalk\n    ) private view returns (uint128 roots) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n\n        // if the stalk is equal to the remaining unclaimed germinating stalk,\n        // then return the remaining unclaimed germinating roots.\n        if (stalk == s.unclaimedGerminating[season].stalk) {\n            roots = s.unclaimedGerminating[season].roots;\n        } else {\n            // calculate the roots:\n            roots = stalk.mul(s.unclaimedGerminating[season].roots).div(\n                s.unclaimedGerminating[season].stalk\n            );\n        }\n    }\n\n    /**\n     * @notice returns the germinatingStalk of the account,\n     * ordered based on the parity of lastUpdate.\n     * @dev if lastUpdate is odd, then `firstStalk` is the odd stalk.\n     */\n    function getGerminatingStalk(\n        address account,\n        bool lastUpdateOdd\n    ) internal view returns (uint128 firstStalk, uint128 secondStalk) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        if (lastUpdateOdd) {\n            firstStalk = s.a[account].farmerGerminating.odd;\n            secondStalk = s.a[account].farmerGerminating.even;\n        } else {\n            firstStalk = s.a[account].farmerGerminating.even;\n            secondStalk = s.a[account].farmerGerminating.odd;\n        }\n    }\n\n    /**\n     * @notice returns the germinating stalk and roots that will finish germinating\n     * upon an interaction with the silo.\n     */\n    function getFinishedGerminatingStalkAndRoots(\n        address account,\n        uint32 lastMowedSeason,\n        uint32 currentSeason\n    ) internal view returns (uint256 germinatingStalk, uint256 germinatingRoots) {\n        // if user has mowed already,\n        // then there are no germinating stalk and roots to finish.\n        if (lastMowedSeason == currentSeason) {\n            return (0, 0);\n        }\n\n        (uint128 firstStalk, uint128 secondStalk) = getGerminatingStalk(\n            account,\n            isSeasonOdd(lastMowedSeason)\n        );\n\n        // check to end germination for first stalk.\n        // if last mowed season is the greater or equal than (currentSeason - 1),\n        // then the first stalk is still germinating.\n        if (firstStalk > 0 && lastMowedSeason < currentSeason.sub(1)) {\n            germinatingStalk = firstStalk;\n            germinatingRoots = calculateGerminatingRoots(lastMowedSeason, firstStalk);\n        }\n\n        // check to end germination for second stalk.\n        if (secondStalk > 0) {\n            germinatingStalk = germinatingStalk.add(secondStalk);\n            germinatingRoots = germinatingRoots.add(\n                calculateGerminatingRoots(lastMowedSeason.sub(1), secondStalk)\n            );\n        }\n    }\n\n    /**\n     * @notice returns the stalk currently germinating for an account.\n     * Does not include germinating stalk that will finish germinating\n     * upon an interaction with the silo.\n     */\n    function getCurrentGerminatingStalk(\n        address account,\n        uint32 lastMowedSeason\n    ) internal view returns (uint256 germinatingStalk) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n\n        // if the last mowed season is less than the current season - 1,\n        // then there are no germinating stalk and roots (as all germinating assets have finished).\n        if (lastMowedSeason < s.season.current.sub(1)) {\n            return 0;\n        } else {\n            (uint128 firstStalk, uint128 secondStalk) = getGerminatingStalk(\n                account,\n                isSeasonOdd(lastMowedSeason)\n            );\n            germinatingStalk = firstStalk.add(secondStalk);\n        }\n    }\n\n    /**\n     * @notice returns the unclaimed germinating stalk and roots.\n     */\n    function getUnclaimedGerminatingStalkAndRoots(\n        uint32 season\n    ) internal view returns (Storage.Sr memory unclaimed) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        unclaimed = s.unclaimedGerminating[season];\n    }\n\n    /**\n     * @notice returns the total germinating bdv and amount for a token.\n     */\n    function getTotalGerminatingForToken(\n        address token\n    ) internal view returns (uint256 bdv, uint256 amount) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        return (\n            s.oddGerminating.deposited[token].bdv.add(s.evenGerminating.deposited[token].bdv),\n            s.oddGerminating.deposited[token].amount.add(s.evenGerminating.deposited[token].amount)\n        );\n    }\n\n    /**\n     * @notice determines whether a deposit (token + stem) should be germinating or not.\n     * If germinating, determines whether the deposit should be set to even or odd.\n     *\n     * @dev `getGerminationState` should be used if the stemTip and germinatingStem\n     * have not been calculated yet. Otherwise, use `_getGerminationState` for gas effiecnecy.\n     */\n    function getGerminationState(\n        address token,\n        int96 stem\n    ) internal view returns (Germinate, int96) {\n        GermStem memory germStem = getGerminatingStem(token);\n        return (_getGerminationState(stem, germStem), germStem.stemTip);\n    }\n\n    /**\n     * @notice returns the `germinating` stem of a token.\n     * @dev the 'germinating' stem is the stem where deposits that have a stem\n     * equal or higher than this value are germinating.\n     */\n    function getGerminatingStem(address token) internal view returns (GermStem memory germStem) {\n        germStem.stemTip = LibTokenSilo.stemTipForToken(token);\n        germStem.germinatingStem = _getGerminatingStem(token, germStem.stemTip);\n    }\n\n    /**\n     * @notice returns the `germinating` stem of a token.\n     * @dev the 'germinating' stem is the stem where deposits that have a stem\n     * equal or higher than this value are germinating.\n     */\n    function _getGerminatingStem(address token, int96 stemTip) internal view returns (int96 stem) {\n        return __getGerminatingStem(stemTip, getPrevStalkEarnedPerSeason(token));\n    }\n\n    /**\n     * @notice Gas efficent version of `_getGerminatingStem`.\n     *\n     * @dev use when the stemTip and germinatingStem have already been calculated.\n     * Assumes the same token is used.\n     * prevStalkEarnedPerSeason is the stalkEarnedPerSeason of the previous season.\n     * since `lastStemTip` + `prevStalkEarnedPerSeason` is the current stemTip, \n     * safeMath is not needed.\n     */\n    function __getGerminatingStem(\n        int96 stemTip,\n        int96 prevStalkEarnedPerSeason\n    ) internal pure returns (int96 stem) {\n        return stemTip - prevStalkEarnedPerSeason;\n    }\n\n    /**\n     * @notice returns the stalkEarnedPerSeason of a token of the previous season.\n     * @dev if the milestone season is not the current season, then the stalkEarnedPerSeason\n     * hasn't changed from the previous season. Otherwise, we calculate the prevStalkEarnedPerSeason.\n     */\n    function getPrevStalkEarnedPerSeason(\n        address token\n    ) private view returns (uint32 prevStalkEarnedPerSeason) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n\n        if (s.ss[token].milestoneSeason < s.season.current) {\n            prevStalkEarnedPerSeason = s.ss[token].stalkEarnedPerSeason;\n        } else {\n            int24 deltaStalkEarnedPerSeason = s.ss[token].deltaStalkEarnedPerSeason;\n            if (deltaStalkEarnedPerSeason >= 0) {\n                prevStalkEarnedPerSeason =\n                    s.ss[token].stalkEarnedPerSeason -\n                    uint32(deltaStalkEarnedPerSeason);\n            } else {\n                prevStalkEarnedPerSeason =\n                    s.ss[token].stalkEarnedPerSeason +\n                    uint32(-deltaStalkEarnedPerSeason);\n            }\n        }\n    }\n\n    /**\n     * @notice internal function for germination stem.\n     * @dev a deposit is germinating if the stem is the stemTip or the germinationStem.\n     * the 'germinationStem` is the stem of the token of the previous season.\n     *\n     * The function must check whether the stem is equal to the germinationStem,\n     * to determine which germination state it is in.\n     */\n    function _getGerminationState(\n        int96 stem,\n        GermStem memory germData\n    ) internal view returns (Germinate) {\n        if (stem < germData.germinatingStem) {\n            // if the stem of the deposit is lower than the germination stem,\n            // then the deposit is not germinating.\n            return Germinate.NOT_GERMINATING;\n        } else {\n            // return the gemination state based on whether the stem\n            // is equal to the stemTip.\n            // if the stem is equal to the stem tip, it is in the initial stages of germination.\n            // if the stem is not equal to the stemTip, its in the germination process.\n            if (stem == germData.stemTip) {\n                return isCurrentSeasonOdd() ? Germinate.ODD : Germinate.EVEN;\n            } else {\n                return isCurrentSeasonOdd() ? Germinate.EVEN : Germinate.ODD;\n            }\n        }\n    }\n\n    /**\n     * @notice returns the germination state for the current season.\n     * @dev used in new deposits, as all new deposits are germinating.\n     */\n    function getSeasonGerminationState() internal view returns (Germinate) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        return getGerminationStateForSeason(s.season.current);\n    }\n\n    /**\n     * @notice returns the germination state for a given season.\n     */\n    function getGerminationStateForSeason(uint32 season) internal pure returns (Germinate) {\n        return isSeasonOdd(season) ? Germinate.ODD : Germinate.EVEN;\n    }\n\n    /**\n     * @notice returns whether the current season is odd. Used for Germination.\n     * @dev even % 2 = 0 (false), odd % 2 = 1 (true)\n     */\n    function isCurrentSeasonOdd() internal view returns (bool) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        return isSeasonOdd(s.season.current);\n    }\n\n    /**\n     * @notice returns whether `season` is odd.\n     */\n    function isSeasonOdd(uint32 season) internal pure returns (bool) {\n        return season.mod(2) == 0 ? false : true;\n    }\n}\n"
      },
      "contracts/libraries/Silo/LibSilo.sol": {
        "content": "/**\n * SPDX-License-Identifier: MIT\n **/\n\npragma solidity =0.7.6;\npragma abicoder v2;\n\nimport \"../LibAppStorage.sol\";\nimport {C} from \"../../C.sol\";\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {SafeCast} from \"@openzeppelin/contracts/utils/SafeCast.sol\";\nimport {LibBytes} from \"../LibBytes.sol\";\nimport {LibTokenSilo} from \"./LibTokenSilo.sol\";\nimport {LibSafeMath128} from \"../LibSafeMath128.sol\";\nimport {LibSafeMath32} from \"../LibSafeMath32.sol\";\nimport {LibSafeMathSigned96} from \"../LibSafeMathSigned96.sol\";\nimport {LibGerminate} from \"./LibGerminate.sol\";\nimport {LibWhitelistedTokens} from \"./LibWhitelistedTokens.sol\";\n\n/**\n * @title LibSilo\n * @author Publius\n * @notice Contains functions for minting, burning, and transferring of\n * Stalk and Roots within the Silo.\n *\n * @dev Here, we refer to \"minting\" as the combination of\n * increasing the total balance of Stalk/Roots, as well as allocating\n * them to a particular account. However, in other places throughout Beanstalk\n * (like during the Sunrise), Beanstalk's total balance of Stalk increases\n * without allocating to a particular account. One example is {Sun-rewardToSilo}\n * which increases `s.s.stalk` but does not allocate it to any account. The\n * allocation occurs during `{SiloFacet-plant}`. Does this change how we should\n * call \"minting\"?\n *\n * In the ERC20 context, \"minting\" increases the supply of a token and allocates\n * the new tokens to an account in one action. I've adjusted the comments below\n * to use \"mint\" in the same sense.\n */\nlibrary LibSilo {\n    using SafeMath for uint256;\n    using LibSafeMath128 for uint128;\n    using LibSafeMathSigned96 for int96;\n    using LibSafeMath32 for uint32;\n    using SafeCast for uint256;\n\n    //////////////////////// ENUM ////////////////////////\n    \n    /**\n     * @dev when a user removes multiple deposits, the\n     * {TransferBatch} event is emitted. However, in the \n     * case of an enroot, the event is omitted (as the \n     * depositID does not change). This enum is\n     * used to determine if the event should be emitted.\n     */\n    enum ERC1155Event {\n        EMIT_BATCH_EVENT,\n        NO_EMIT_BATCH_EVENT\n    }\n    \n\n    uint128 internal constant PRECISION = 1e6;\n    //////////////////////// EVENTS ////////////////////////\n\n    /**\n     * @notice Emitted when `account` gains or loses Stalk.\n     * @param account The account that gained or lost Stalk.\n     * @param delta The change in Stalk.\n     * @param deltaRoots The change in Roots.\n     *\n     * @dev Should be emitted anytime a Deposit is added, removed or transferred\n     * AND anytime an account Mows Grown Stalk.\n     *\n     * BIP-24 included a one-time re-emission of {StalkBalanceChanged} for\n     * accounts that had executed a Deposit transfer between the Replant and\n     * BIP-24 execution. For more, see:\n     *\n     * [BIP-24](https://bean.money/bip-24)\n     * [Event-Emission](https://github.com/BeanstalkFarms/BIP-24-Event-Emission)\n     */\n    event StalkBalanceChanged(address indexed account, int256 delta, int256 deltaRoots);\n\n    /**\n     * @notice Emitted when a deposit is removed from the silo.\n     *\n     * @param account The account assoicated with the removed deposit.\n     * @param token The token address of the removed deposit.\n     * @param stem The stem of the removed deposit.\n     * @param amount The amount of \"token\" removed from an deposit.\n     * @param bdv The instanteous bdv removed from the deposit.\n     */\n    event RemoveDeposit(\n        address indexed account,\n        address indexed token,\n        int96 stem,\n        uint256 amount,\n        uint256 bdv\n    );\n\n    /**\n     * @notice Emitted when multiple deposits are removed from the silo.\n     *\n     * @param account The account assoicated with the removed deposit.\n     * @param token The token address of the removed deposit.\n     * @param stems A list of stems of the removed deposits.\n     * @param amounts A list of amounts removed from the deposits.\n     * @param amount the total summation of the amount removed.\n     * @param bdvs A list of bdvs removed from the deposits.\n     */\n    event RemoveDeposits(\n        address indexed account,\n        address indexed token,\n        int96[] stems,\n        uint256[] amounts,\n        uint256 amount,\n        uint256[] bdvs\n    );\n\n    /**\n     * AssetsRemoved contains the assets removed \n     * during a withdraw or convert. \n     * \n     * @dev seperated into 3 catagories:\n     * active: non-germinating assets.\n     * odd: odd germinating assets.\n     * even: even germinating assets.\n     * grownStalk from germinating depoists are seperated \n     * as that stalk is not germinating.\n     */\n    struct AssetsRemoved {\n        Removed active;\n        Removed odd; \n        Removed even;\n        uint256 grownStalkFromGermDeposits;\n    }\n\n    struct Removed {\n        uint256 tokens;\n        uint256 stalk;\n        uint256 bdv;\n    }\n\n    /**\n     * @notice Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all\n     * transfers.\n     */\n    event TransferBatch(\n        address indexed operator,\n        address indexed from,\n        address indexed to,\n        uint256[] ids,\n        uint256[] values\n    );\n\n    //////////////////////// MINT ////////////////////////\n\n   \n    /**\n     * @dev Mints Stalk and Roots to `account`.\n     *\n     * `roots` are an underlying accounting variable that is used to track\n     * how many earned beans a user has.\n     *\n     * When a farmer's state is updated, the ratio should hold:\n     *\n     *  Total Roots     User Roots\n     * ------------- = ------------\n     *  Total Stalk     User Stalk\n     *\n     * @param account the address to mint Stalk and Roots to\n     * @param stalk the amount of stalk to mint\n     *\n     * @dev Stalk that is not germinating are `active`, meaning that they \n     * are eligible for bean mints. To mint germinating stalk, use \n     * `mintGerminatingStalk`.\n     */\n    function mintActiveStalk(address account, uint256 stalk) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        uint256 roots;\n        if (s.s.roots == 0) {\n            roots = uint256(stalk.mul(C.getRootsBase()));\n        } else {\n            // germinating assets should be considered\n            // when calculating roots\n            roots = s.s.roots.mul(stalk).div(s.s.stalk);\n        }\n\n        // increment user and total stalk;\n        s.s.stalk = s.s.stalk.add(stalk);\n        s.a[account].s.stalk = s.a[account].s.stalk.add(stalk);\n\n        // increment user and total roots\n        s.s.roots = s.s.roots.add(roots);\n        s.a[account].roots = s.a[account].roots.add(roots);\n\n        emit StalkBalanceChanged(account, int256(stalk), int256(roots));\n    }\n\n    /**\n     * @notice mintGerminatingStalk contains logic for minting stalk that is germinating.\n     * @dev `germinating stalk` are newly issued stalk that are not eligible for bean mints,\n     * until 2 `gm` calls have passed, at which point they are considered `grown stalk`.\n     *\n     * Since germinating stalk are not elgible for bean mints, when calculating the roots of these\n     * stalk, it should use the stalk and roots of the system once the stalk is fully germinated,\n     * rather than at the time of minting.\n     */\n    function mintGerminatingStalk(\n        address account,\n        uint128 stalk,\n        LibGerminate.Germinate germ\n    ) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n\n        if (germ == LibGerminate.Germinate.ODD) {\n            s.a[account].farmerGerminating.odd = s.a[account].farmerGerminating.odd.add(stalk);\n        } else {\n            s.a[account].farmerGerminating.even = s.a[account].farmerGerminating.even.add(stalk);\n        }\n\n        // germinating stalk are either newly germinating, or partially germinated.\n        // Thus they can only be incremented in the latest or previous season.\n        uint32 germinationSeason = s.season.current;\n        if (LibGerminate.getSeasonGerminationState() == germ) {\n            s.unclaimedGerminating[germinationSeason].stalk =\n                s.unclaimedGerminating[germinationSeason].stalk.add(stalk);\n        } else {\n            germinationSeason = germinationSeason.sub(1);\n            s.unclaimedGerminating[germinationSeason].stalk = \n                s.unclaimedGerminating[germinationSeason].stalk\n                .add(stalk);\n        }\n\n        // emit events.\n        emit LibGerminate.FarmerGerminatingStalkBalanceChanged(account, stalk, germ);\n        emit LibGerminate.TotalGerminatingStalkChanged(germinationSeason, stalk);\n    }\n\n    //////////////////////// BURN ////////////////////////\n\n    /**\n     * @notice Burns stalk and roots from an account.\n     */\n    function burnActiveStalk(address account, uint256 stalk) internal returns (uint256 roots) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        if (stalk == 0) return 0;\n\n        // Calculate the amount of Roots for the given amount of Stalk.\n        roots = s.s.roots.mul(stalk).div(s.s.stalk);\n        if (roots > s.a[account].roots) roots = s.a[account].roots;\n\n        // Decrease supply of Stalk; Remove Stalk from the balance of `account`\n        s.s.stalk = s.s.stalk.sub(stalk);\n        s.a[account].s.stalk = s.a[account].s.stalk.sub(stalk);\n\n        // Decrease supply of Roots; Remove Roots from the balance of `account`\n        s.s.roots = s.s.roots.sub(roots);\n        s.a[account].roots = s.a[account].roots.sub(roots);\n\n        // emit event.\n        emit StalkBalanceChanged(account, -int256(stalk), -int256(roots));\n    }\n\n    /**\n     * @notice Burns germinating stalk.\n     * @dev Germinating stalk does not have any roots assoicated with it.\n     */\n    function burnGerminatingStalk(\n        address account,\n        uint128 stalk,\n        LibGerminate.Germinate germ\n    ) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n\n        if (germ == LibGerminate.Germinate.ODD) {\n            s.a[account].farmerGerminating.odd = s.a[account].farmerGerminating.odd.sub(stalk);\n        } else {\n            s.a[account].farmerGerminating.even = s.a[account].farmerGerminating.even.sub(stalk);\n        }\n\n        // germinating stalk are either newly germinating, or partially germinated.\n        // Thus they can only be decremented in the latest or previous season.\n        uint32 germinationSeason = s.season.current;\n        if (LibGerminate.getSeasonGerminationState() == germ) {\n            s.unclaimedGerminating[germinationSeason].stalk = \n                s.unclaimedGerminating[germinationSeason].stalk.sub(stalk);\n        } else {\n            germinationSeason = germinationSeason.sub(1);\n            s.unclaimedGerminating[germinationSeason].stalk = \n                s.unclaimedGerminating[germinationSeason].stalk\n                .sub(stalk);\n        }\n\n        // emit events.\n        emit LibGerminate.FarmerGerminatingStalkBalanceChanged(account, -int256(stalk), germ);\n        emit LibGerminate.TotalGerminatingStalkChanged(germinationSeason, -int256(stalk));\n    }\n\n    //////////////////////// TRANSFER ////////////////////////\n\n    /**\n     * @notice Decrements the Stalk and Roots of `sender` and increments the Stalk\n     * and Roots of `recipient` by the same amount.\n     *\n     */\n    function transferStalk(address sender, address recipient, uint256 stalk) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        uint256 roots;\n        roots = stalk == s.a[sender].s.stalk\n            ? s.a[sender].roots\n            : s.s.roots.sub(1).mul(stalk).div(s.s.stalk).add(1);\n\n        // Subtract Stalk and Roots from the 'sender' balance.\n        s.a[sender].s.stalk = s.a[sender].s.stalk.sub(stalk);\n        s.a[sender].roots = s.a[sender].roots.sub(roots);\n        emit StalkBalanceChanged(sender, -int256(stalk), -int256(roots));\n\n        // Add Stalk and Roots to the 'recipient' balance.\n        s.a[recipient].s.stalk = s.a[recipient].s.stalk.add(stalk);\n        s.a[recipient].roots = s.a[recipient].roots.add(roots);\n        emit StalkBalanceChanged(recipient, int256(stalk), int256(roots));\n    }\n\n    /**\n     * @notice germinating counterpart of `transferStalk`.\n     * @dev assumes stalk is germinating.\n     */\n    function transferGerminatingStalk(\n        address sender,\n        address recipient,\n        uint256 stalk,\n        LibGerminate.Germinate germState\n    ) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n         // Subtract Germinating Stalk from the 'sender' balance, \n         // and Add to the 'recipient' balance.\n        if (germState == LibGerminate.Germinate.ODD) {\n            s.a[sender].farmerGerminating.odd = s.a[sender].farmerGerminating.odd.sub(stalk.toUint128());\n            s.a[recipient].farmerGerminating.odd = s.a[recipient].farmerGerminating.odd.add(stalk.toUint128());\n        } else {\n            s.a[sender].farmerGerminating.even = s.a[sender].farmerGerminating.even.sub(stalk.toUint128());\n            s.a[recipient].farmerGerminating.even = s.a[recipient].farmerGerminating.even.add(stalk.toUint128());\n        }\n\n        // emit events.\n        emit LibGerminate.FarmerGerminatingStalkBalanceChanged(sender, -int256(stalk), germState);\n        emit LibGerminate.FarmerGerminatingStalkBalanceChanged(recipient, int256(stalk), germState);\n    }\n\n    /**\n     * @notice transfers both stalk and Germinating Stalk.\n     * @dev used in {TokenSilo._transferDeposits}\n     */\n    function transferStalkAndGerminatingStalk(\n        address sender,\n        address recipient,\n        address token,\n        AssetsRemoved memory ar\n    ) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        uint256 stalkPerBDV = s.ss[token].stalkIssuedPerBdv;\n\n        // a germinating deposit may have active grown stalk,\n        // but no active stalk from bdv.\n        if (ar.active.stalk > 0) {\n            ar.active.stalk = ar.active.stalk.add(ar.active.bdv.mul(stalkPerBDV));\n            transferStalk(sender, recipient, ar.active.stalk);\n        }\n\n        if (ar.odd.bdv > 0) {\n            ar.odd.stalk = ar.odd.stalk.add(ar.odd.bdv.mul(stalkPerBDV));\n            transferGerminatingStalk(\n                sender,\n                recipient,\n                ar.odd.stalk,\n                LibGerminate.Germinate.ODD\n            );\n        }\n\n        if (ar.even.bdv > 0) {\n            ar.even.stalk = ar.even.stalk.add(ar.even.bdv.mul(stalkPerBDV));\n            transferGerminatingStalk(\n                sender,\n                recipient,\n                ar.even.stalk,\n                LibGerminate.Germinate.EVEN\n            );\n        }\n    }\n\n    /**\n     * @dev Claims the Grown Stalk for `account` and applies it to their Stalk\n     * balance. Also handles Season of Plenty related rain.\n     *\n     * This is why `_mow()` must be called before any actions that change Seeds,\n     * including:\n     *  - {SiloFacet-deposit}\n     *  - {SiloFacet-withdrawDeposit}\n     *  - {SiloFacet-withdrawDeposits}\n     *  - {_plant}\n     *  - {SiloFacet-transferDeposit(s)}\n     */\n    function _mow(address account, address token) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        \n        // if the user has not migrated from siloV2, revert.\n        (bool needsMigration, uint32 lastUpdate) = migrationNeeded(account);\n        require(!needsMigration, \"Silo: Migration needed\");\n\n        // if the user hasn't updated prior to the seedGauge/siloV3.1 update,\n        // perform a one time `lastStem` scale.\n        if (\n            (lastUpdate < s.season.stemScaleSeason && lastUpdate > 0) || \n            (lastUpdate == s.season.stemScaleSeason && checkStemEdgeCase(account))\n        ) {\n            migrateStems(account);\n        }\n\n        // sop data only needs to be updated once per season,\n        // if it started raining and it's still raining, or there was a sop\n        uint32 currentSeason = s.season.current;\n        if (s.season.rainStart > s.season.stemStartSeason) {\n            if (lastUpdate <= s.season.rainStart && lastUpdate <= currentSeason) {\n                // Increments `plenty` for `account` if a Flood has occured.\n                // Saves Rain Roots for `account` if it is Raining.\n                handleRainAndSops(account, lastUpdate);\n            }\n        }\n        \n        // End account germination.\n        if (lastUpdate < currentSeason) {\n            LibGerminate.endAccountGermination(account, lastUpdate, currentSeason);\n        }\n        // Calculate the amount of Grown Stalk claimable by `account`.\n        // Increase the account's balance of Stalk and Roots.\n        __mow(account, token);\n\n        // update lastUpdate for sop and germination calculations.\n        s.a[account].lastUpdate = currentSeason;\n    }\n\n    /**\n     * @dev Updates the mowStatus for the given account and token,\n     * and mints Grown Stalk for the given account and token.\n     */\n    function __mow(\n        address account,\n        address token\n    ) private {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n\n        int96 _stemTip = LibTokenSilo.stemTipForToken(token);\n        int96 _lastStem = s.a[account].mowStatuses[token].lastStem;\n        uint128 _bdv = s.a[account].mowStatuses[token].bdv;\n\n        // if:\n        // 1: account has no bdv (new token deposit)\n        // 2: the lastStem is the same as the stemTip (implying that a user has mowed),\n        // then skip calculations to save gas.\n        if (_bdv > 0) {\n            if (_lastStem == _stemTip) {\n                return;\n            }\n\n            // grown stalk does not germinate and is immediately included for bean mints.\n            mintActiveStalk(account, _balanceOfGrownStalk(_lastStem, _stemTip, _bdv));\n        }\n\n        // If this `account` has no BDV, skip to save gas. Update lastStem.\n        // (happen on initial deposit, since mow is called before any deposit)\n        s.a[account].mowStatuses[token].lastStem = _stemTip;\n        return;\n    }\n\n    /**\n     * @notice returns the last season an account interacted with the silo.\n     */\n    function _lastUpdate(address account) internal view returns (uint32) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        return s.a[account].lastUpdate;\n    }\n\n    /**\n     * @dev internal logic to handle when beanstalk is raining.\n     */\n    function handleRainAndSops(address account, uint32 lastUpdate) private {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        // If no roots, reset Sop counters variables\n        if (s.a[account].roots == 0) {\n            s.a[account].lastSop = s.season.rainStart;\n            s.a[account].lastRain = 0;\n            return;\n        }\n        // If a Sop has occured since last update, calculate rewards and set last Sop.\n        if (s.season.lastSopSeason > lastUpdate) {\n            s.a[account].sop.plenty = balanceOfPlenty(account);\n            s.a[account].lastSop = s.season.lastSop;\n        }\n        if (s.season.raining) {\n            // If rain started after update, set account variables to track rain.\n            if (s.season.rainStart > lastUpdate) {\n                s.a[account].lastRain = s.season.rainStart;\n                s.a[account].sop.roots = s.a[account].roots;\n            }\n            // If there has been a Sop since rain started,\n            // save plentyPerRoot in case another SOP happens during rain.\n            if (s.season.lastSop == s.season.rainStart) {\n                s.a[account].sop.plentyPerRoot = s.sops[s.season.lastSop];\n            }\n        } else if (s.a[account].lastRain > 0) {\n            // Reset Last Rain if not raining.\n            s.a[account].lastRain = 0;\n        }\n    }\n\n    /**\n     * @dev returns the balance of amount of grown stalk based on stems.\n     * @param lastStem the stem assoicated with the last mow\n     * @param latestStem the current stem for a given token\n     * @param bdv the bdv used to calculate grown stalk\n     */\n    function _balanceOfGrownStalk(\n        int96 lastStem,\n        int96 latestStem,\n        uint128 bdv\n    ) internal pure returns (uint256) {\n        return stalkReward(lastStem, latestStem, bdv);\n    }\n\n    /**\n     * @dev returns the amount of `plenty` an account has.\n     */\n    function balanceOfPlenty(address account) internal view returns (uint256 plenty) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        Account.State storage a = s.a[account];\n        plenty = a.sop.plenty;\n        uint256 previousPPR;\n\n        // If lastRain > 0, then check if SOP occured during the rain period.\n        if (s.a[account].lastRain > 0) {\n            // if the last processed SOP = the lastRain processed season,\n            // then we use the stored roots to get the delta.\n            if (a.lastSop == a.lastRain) previousPPR = a.sop.plentyPerRoot;\n            else previousPPR = s.sops[a.lastSop];\n            uint256 lastRainPPR = s.sops[s.a[account].lastRain];\n\n            // If there has been a SOP duing the rain sesssion since last update, process SOP.\n            if (lastRainPPR > previousPPR) {\n                uint256 plentyPerRoot = lastRainPPR - previousPPR;\n                previousPPR = lastRainPPR;\n                plenty = plenty.add(plentyPerRoot.mul(s.a[account].sop.roots).div(C.SOP_PRECISION));\n            }\n        } else {\n            // If it was not raining, just use the PPR at previous SOP.\n            previousPPR = s.sops[s.a[account].lastSop];\n        }\n\n        // Handle and SOPs that started + ended before after last Silo update.\n        if (s.season.lastSop > _lastUpdate(account)) {\n            uint256 plentyPerRoot = s.sops[s.season.lastSop].sub(previousPPR);\n            plenty = plenty.add(plentyPerRoot.mul(s.a[account].roots).div(C.SOP_PRECISION));\n        }\n    }\n\n    //////////////////////// REMOVE ////////////////////////\n\n    /**\n     * @dev Removes from a single Deposit, emits the RemoveDeposit event,\n     * and returns the Stalk/BDV that were removed.\n     *\n     * Used in:\n     * - {TokenSilo:_withdrawDeposit}\n     * - {TokenSilo:_transferDeposit}\n     */\n    function _removeDepositFromAccount(\n        address account,\n        address token,\n        int96 stem,\n        uint256 amount,\n        LibTokenSilo.Transfer transferType\n    )\n        internal\n        returns (\n            uint256 initialStalkRemoved,\n            uint256 grownStalkRemoved,\n            uint256 bdvRemoved,\n            LibGerminate.Germinate germ\n        )\n    {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        int96 stemTip;\n        (germ, stemTip) = LibGerminate.getGerminationState(token, stem);\n        bdvRemoved = LibTokenSilo.removeDepositFromAccount(account, token, stem, amount);\n\n        // the initial and grown stalk are as there are instances where the initial stalk is\n        // germinating, but the grown stalk is not.\n        initialStalkRemoved = bdvRemoved.mul(s.ss[token].stalkIssuedPerBdv);\n\n        grownStalkRemoved = stalkReward(stem, stemTip, bdvRemoved.toUint128());\n        /**\n         *  {_removeDepositFromAccount} is used for both withdrawing and transferring deposits.\n         *  In the case of a withdraw, only the {TransferSingle} Event needs to be emitted.\n         *  In the case of a transfer, a different {TransferSingle}/{TransferBatch}\n         *  Event is emitted in {TokenSilo._transferDeposit(s)},\n         *  and thus, this event is ommited.\n         */\n        if (transferType == LibTokenSilo.Transfer.emitTransferSingle) {\n            // \"removing\" a deposit is equivalent to \"burning\" an ERC1155 token.\n            emit LibTokenSilo.TransferSingle(\n                msg.sender, // operator\n                account, // from\n                address(0), // to\n                LibBytes.packAddressAndStem(token, stem), // depositid\n                amount // token amount\n            );\n        }\n        emit RemoveDeposit(account, token, stem, amount, bdvRemoved);\n    }\n\n    /**\n     * @dev Removes from multiple Deposits, emits the RemoveDeposits\n     * event, and returns the Stalk/BDV that were removed.\n     *\n     * Used in:\n     * - {TokenSilo:_withdrawDeposits}\n     * - {SiloFacet:enrootDeposits}\n     *\n     * @notice with the addition of germination, AssetsRemoved\n     * keeps track of the germinating data.\n     */\n    function _removeDepositsFromAccount(\n        address account,\n        address token,\n        int96[] calldata stems,\n        uint256[] calldata amounts,\n        ERC1155Event emission\n    ) internal returns (AssetsRemoved memory ar) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n\n        uint256[] memory bdvsRemoved = new uint256[](stems.length);\n        uint256[] memory removedDepositIDs = new uint256[](stems.length);\n        LibGerminate.GermStem memory germStem = LibGerminate.getGerminatingStem(token);\n        for (uint256 i; i < stems.length; ++i) {\n            LibGerminate.Germinate germState = LibGerminate._getGerminationState(\n                stems[i],\n                germStem\n            );\n            uint256 crateBdv = LibTokenSilo.removeDepositFromAccount(\n                account,\n                token,\n                stems[i],\n                amounts[i]\n            );\n            bdvsRemoved[i] = crateBdv;\n            removedDepositIDs[i] = LibBytes.packAddressAndStem(token, stems[i]);\n            uint256 crateStalk = stalkReward(stems[i], germStem.stemTip, crateBdv.toUint128());\n\n            // if the deposit is germinating, decrement germinating values,\n            // otherwise increment deposited values.\n            if (germState == LibGerminate.Germinate.NOT_GERMINATING) {\n                ar.active.bdv = ar.active.bdv.add(crateBdv);\n                ar.active.stalk = ar.active.stalk.add(crateStalk);\n                ar.active.tokens = ar.active.tokens.add(amounts[i]);\n            } else {\n                if (germState == LibGerminate.Germinate.ODD) {\n                    ar.odd.bdv = ar.odd.bdv.add(crateBdv);\n                    ar.odd.tokens = ar.odd.tokens.add(amounts[i]);\n                } else {\n                    ar.even.bdv = ar.even.bdv.add(crateBdv);\n                    ar.even.tokens = ar.even.tokens.add(amounts[i]);\n                }\n                // grown stalk from germinating deposits do not germinate,\n                // and thus must be added to the grown stalk.\n                ar.grownStalkFromGermDeposits = ar.grownStalkFromGermDeposits.add(\n                    crateStalk\n                );\n            }\n        }\n\n        // add initial stalk deposit to all stalk removed.\n        {\n            uint256 stalkIssuedPerBdv = s.ss[token].stalkIssuedPerBdv;\n            if (ar.active.tokens > 0) {\n                ar.active.stalk = ar.active.stalk.add(ar.active.bdv.mul(stalkIssuedPerBdv));\n            }\n\n            if (ar.odd.tokens > 0) {\n                ar.odd.stalk = ar.odd.bdv.mul(stalkIssuedPerBdv);\n            }\n\n            if (ar.even.tokens > 0) {\n                ar.even.stalk = ar.even.bdv.mul(stalkIssuedPerBdv);\n            }\n        }\n\n        // \"removing\" deposits is equivalent to \"burning\" a batch of ERC1155 tokens.\n        if (emission == ERC1155Event.EMIT_BATCH_EVENT) {\n            emit TransferBatch(msg.sender, account, address(0), removedDepositIDs, amounts);\n        }\n\n        emit RemoveDeposits(\n            account, \n            token, \n            stems, \n            amounts,\n            ar.active.tokens.add(ar.odd.tokens).add(ar.even.tokens), \n            bdvsRemoved\n        );\n    }\n\n    //////////////////////// UTILITIES ////////////////////////\n\n    /**\n     * @notice Calculates the Stalk reward based on the start and end\n     * stems, and the amount of BDV deposited. Stems represent the\n     * amount of grown stalk per BDV, so the difference between the\n     * start index and end index (stem) multiplied by the amount of\n     * bdv deposited will give the amount of stalk earned.\n     * formula: stalk = bdv * (ΔstalkPerBdv)\n     * \n     * @dev endStem must be larger than startStem.\n     * \n     */\n    function stalkReward(\n        int96 startStem,\n        int96 endStem,\n        uint128 bdv\n    ) internal pure returns (uint256) {\n        uint128 reward = uint128(endStem.sub(startStem)).mul(bdv).div(PRECISION);\n\n        return reward;\n    }\n\n    /**\n     * @dev check whether the account needs to be migrated.\n     */\n    function migrationNeeded(address account) internal view returns (bool needsMigration, uint32 lastUpdate) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        lastUpdate = s.a[account].lastUpdate;\n        needsMigration = lastUpdate > 0 && lastUpdate < s.season.stemStartSeason;\n    }\n\n    /**\n     * @dev Internal function to compute `account` balance of Earned Beans.\n     *\n     * The number of Earned Beans is equal to the difference between:\n     *  - the \"expected\" Stalk balance, determined from the account balance of\n     *    Roots.\n     *  - the \"account\" Stalk balance, stored in account storage.\n     * divided by the number of Stalk per Bean.\n     * The earned beans from the latest season\n     */\n    function _balanceOfEarnedBeans(\n        uint256 accountStalk,\n        uint256 accountRoots\n    ) internal view returns (uint256 beans) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        // There will be no Roots before the first Deposit is made.\n        if (s.s.roots == 0) return 0;\n\n        uint256 stalk = s.s.stalk.mul(accountRoots).div(s.s.roots);\n\n        // Beanstalk rounds down when minting Roots. Thus, it is possible that\n        // balanceOfRoots / totalRoots * totalStalk < s.a[account].s.stalk.\n        // As `account` Earned Balance balance should never be negative,\n        // Beanstalk returns 0 instead.\n        if (stalk <= accountStalk) return 0;\n\n        // Calculate Earned Stalk and convert to Earned Beans.\n        beans = (stalk - accountStalk).div(C.STALK_PER_BEAN); // Note: SafeMath is redundant here.\n        if (beans > s.earnedBeans) return s.earnedBeans;\n\n        return beans;\n    }\n\n    /**\n     * @notice performs a one time update for the\n     * users lastStem for all silo Tokens.\n     * @dev Due to siloV3.1 update.\n     */\n    function migrateStems(address account) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        address[] memory siloTokens = LibWhitelistedTokens.getSiloTokens();\n        for(uint i; i < siloTokens.length; i++) {\n            // scale lastStem by 1e6, if the user has a lastStem.\n            if (s.a[account].mowStatuses[siloTokens[i]].lastStem > 0) { \n                s.a[account].mowStatuses[siloTokens[i]].lastStem = \n                    s.a[account].mowStatuses[siloTokens[i]].lastStem.mul(int96(PRECISION));\n            }\n        }\n    }\n\n    /**\n     * @dev An edge case can occur with the siloV3.1 update, where\n     * A user updates their silo in the same season as the seedGauge update,\n     * but prior to the seedGauge BIP execution (i.e the farmer mowed at the start of\n     * the season, and the BIP was excuted mid-way through the season).\n     * This function checks for that edge case and returns a boolean.\n     */\n    function checkStemEdgeCase(address account) internal view returns (bool) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        address[] memory siloTokens = LibWhitelistedTokens.getSiloTokens();\n        // for each silo token, divide the stemTip of the token with the users last stem.\n        // if the answer is 1e6 or greater, the user has not updated.\n        for(uint i; i < siloTokens.length; i++) {\n            int96 lastStem = s.a[account].mowStatuses[siloTokens[i]].lastStem;\n            if (lastStem > 0) {\n                if (LibTokenSilo.stemTipForToken(siloTokens[i]).div(lastStem) >= int96(PRECISION)) {\n                    return true;\n                }\n            }\n        }\n        return false;\n    }\n}\n"
      },
      "contracts/libraries/Silo/LibTokenSilo.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 {SafeCast} from \"@openzeppelin/contracts/utils/SafeCast.sol\";\nimport {LibAppStorage, Storage, AppStorage, Account} from \"../LibAppStorage.sol\";\nimport {C} from \"../../C.sol\";\nimport {LibSafeMath32} from \"contracts/libraries/LibSafeMath32.sol\";\nimport {LibSafeMath128} from \"contracts/libraries/LibSafeMath128.sol\";\nimport {LibSafeMathSigned128} from \"contracts/libraries/LibSafeMathSigned128.sol\";\nimport {LibSafeMathSigned96} from \"contracts/libraries/LibSafeMathSigned96.sol\";\nimport {LibBytes} from \"contracts/libraries/LibBytes.sol\";\nimport {LibGerminate} from \"contracts/libraries/Silo/LibGerminate.sol\";\nimport {LibWhitelistedTokens} from \"contracts/libraries/Silo/LibWhitelistedTokens.sol\";\n\n/**\n * @title LibTokenSilo\n * @author Publius, Pizzaman1337\n * @notice Contains functions for depositing, withdrawing and claiming\n * whitelisted Silo tokens.\n *\n * For functionality related to Stalk, and Roots, see {LibSilo}.\n */\nlibrary LibTokenSilo {\n    using SafeMath for uint256;\n    using LibSafeMath128 for uint128;\n    using LibSafeMath32 for uint32;\n    using LibSafeMathSigned128 for int128;\n    using SafeCast for int128;\n    using SafeCast for uint256;\n    using LibSafeMathSigned96 for int96;\n\n    uint256 constant PRECISION = 1e6; // increased precision from to silo v3.1.\n\n\n    //////////////////////// ENUM ////////////////////////\n    /**\n     * @dev when a user deposits or withdraws a deposit, the\n     * {TrasferSingle} event is emitted. However, in the case\n     * of a transfer, this emission is ommited. This enum is\n     * used to determine if the event should be emitted.\n     */\n    enum Transfer {\n        emitTransferSingle,\n        noEmitTransferSingle\n    }\n\n    //////////////////////// EVENTS ////////////////////////\n\n    /**\n     * @dev IMPORTANT: copy of {TokenSilo-AddDeposit}, check there for details.\n     */\n    event AddDeposit(\n        address indexed account,\n        address indexed token,\n        int96 stem,\n        uint256 amount,\n        uint256 bdv\n    );\n\n    /**\n     * @dev IMPORTANT: copy of {TokenSilo-RemoveDeposit}, check there for details.\n     */\n    event RemoveDeposit(\n        address indexed account,\n        address indexed token,\n        int96 stem,\n        uint256 amount,\n        uint256 bdv\n    );\n\n    // added as the ERC1155 deposit upgrade\n    event TransferSingle(\n        address indexed operator,\n        address indexed sender,\n        address indexed recipient,\n        uint256 depositId,\n        uint256 amount\n    );\n\n    //////////////////////// ACCOUNTING: TOTALS GERMINATING ////////////////////////\n\n    /**\n     * @notice Increment the total amount and bdv of `token` germinating in the Silo.\n     * @dev when an asset is `deposited` in the silo, it is not immediately eliable for\n     * bean mints. It must `germinate` (stay deposited the silo) for a certain\n     * amount of seasons (the remainer of the current season + 1). This function\n     * increments the total amount and bdv germinating in the silo. The {sunrise}\n     * function ends the germination process for even or odd germinating deposits.\n     *\n     * This protects beanstalk from flashloan attacks, and makes `totalDeposited` and\n     * `totalDepositedBdv` significantly more MEV resistant.\n     */\n    function incrementTotalGerminating(\n        address token,\n        uint256 amount,\n        uint256 bdv,\n        LibGerminate.Germinate germ\n    ) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        Storage.TotalGerminating storage germinate;\n\n        // verify germ is valid\n        if (germ == LibGerminate.Germinate.ODD) {\n            germinate = s.oddGerminating;\n        } else if (germ == LibGerminate.Germinate.EVEN) {\n            germinate = s.evenGerminating;\n        } else {\n            revert(\"invalid germinationMode\"); // should not ever get here\n        }\n\n        // increment germinating amount and bdv.\n        germinate.deposited[token].amount = germinate.deposited[token].amount.add(\n            amount.toUint128()\n        );\n        germinate.deposited[token].bdv = germinate.deposited[token].bdv.add(bdv.toUint128());\n\n        // emit event.\n        emit LibGerminate.TotalGerminatingBalanceChanged(\n            s.season.current,\n            token,\n            int256(amount),\n            int256(bdv)\n        );\n    }\n\n    /**\n     * @notice Decrement the total amount and bdv of `token` germinating in the Silo.\n     * @dev `decrementTotalGerminating` should be used when removing deposits\n     * that are < 2 seasons old.\n     */\n    function decrementTotalGerminating(\n        address token,\n        uint256 amount,\n        uint256 bdv,\n        LibGerminate.Germinate germ\n    ) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        Storage.TotalGerminating storage germinate;\n\n        // verify germ is valid\n        if (germ == LibGerminate.Germinate.ODD) {\n            germinate = s.oddGerminating;\n        } else if (germ == LibGerminate.Germinate.EVEN) {\n            germinate = s.evenGerminating;\n        } else {\n            revert(\"invalid germinationMode\"); // should not ever get here\n        }\n\n        // decrement germinating amount and bdv.\n        germinate.deposited[token].amount = germinate.deposited[token].amount.sub(\n            amount.toUint128()\n        );\n        germinate.deposited[token].bdv = germinate.deposited[token].bdv.sub(bdv.toUint128());\n    \n        emit LibGerminate.TotalGerminatingBalanceChanged(\n            LibGerminate.getSeasonGerminationState() == germ ? \n                s.season.current : \n                s.season.current - 1,\n            token,\n            -int256(amount),\n            -int256(bdv)\n        );\n    }\n\n    /**\n     * @notice Increment the total bdv of `token` germinating in the Silo. Used in Enroot.\n     */\n    function incrementTotalGerminatingBdv(\n        address token,\n        uint256 bdv,\n        LibGerminate.Germinate germ\n    ) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n\n        if (germ == LibGerminate.Germinate.ODD) {\n            // increment odd germinating\n            s.oddGerminating.deposited[token].bdv = s.oddGerminating.deposited[token].bdv.add(\n                bdv.toUint128()\n            );\n        } else if (germ == LibGerminate.Germinate.EVEN) {\n            // increment even germinating\n            s.evenGerminating.deposited[token].bdv = s.evenGerminating.deposited[token].bdv.add(\n                bdv.toUint128()\n            );\n        } else {\n            revert(\"invalid germinationMode\"); // should not ever get here\n        }\n\n        emit LibGerminate.TotalGerminatingBalanceChanged(\n            LibGerminate.getSeasonGerminationState() == germ ? \n                s.season.current : \n                s.season.current - 1,\n            token,\n            0,\n            int256(bdv)\n        );\n    }\n\n    //////////////////////// ACCOUNTING: TOTALS ////////////////////////\n\n    /**\n     * @dev Increment the total amount and bdv of `token` deposited in the Silo.\n     * @dev `IncrementTotalDeposited` should be used when removing deposits that are\n     * >= 2 seasons old (ex. when a user converts).\n     */\n    function incrementTotalDeposited(address token, uint256 amount, uint256 bdv) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        s.siloBalances[token].deposited = s.siloBalances[token].deposited.add(amount.toUint128());\n        s.siloBalances[token].depositedBdv = s.siloBalances[token].depositedBdv.add(\n            bdv.toUint128()\n        );\n    }\n\n    /**\n     * @notice Decrement the total amount and bdv of `token` deposited in the Silo.\n     * @dev `decrementTotalDeposited` should be used when removing deposits that are\n     * >= 2 seasons old.\n     */\n    function decrementTotalDeposited(address token, uint256 amount, uint256 bdv) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        s.siloBalances[token].deposited = s.siloBalances[token].deposited.sub(amount.toUint128());\n        s.siloBalances[token].depositedBdv = s.siloBalances[token].depositedBdv.sub(\n            bdv.toUint128()\n        );\n    }\n\n    /**\n     * @notice Increment the total bdv of `token` deposited in the Silo. Used in Enroot.\n     */\n    function incrementTotalDepositedBdv(address token, uint256 bdv) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        s.siloBalances[token].depositedBdv = s.siloBalances[token].depositedBdv.add(\n            bdv.toUint128()\n        );\n    }\n\n    //////////////////////// ADD DEPOSIT ////////////////////////\n\n    /**\n     * @return stalk The amount of Stalk received for this Deposit.\n     *\n     * @dev Calculate the current BDV for `amount` of `token`, then perform\n     * Deposit accounting.\n     */\n    function deposit(\n        address account,\n        address token,\n        int96 stem,\n        uint256 amount\n    ) internal returns (uint256, LibGerminate.Germinate) {\n        uint256 bdv = beanDenominatedValue(token, amount);\n        return depositWithBDV(account, token, stem, amount, bdv);\n    }\n\n    /**\n     * @dev Once the BDV received for Depositing `amount` of `token` is known,\n     * add a Deposit for `account` and update the total amount Deposited.\n     *\n     * `s.ss[token].stalkIssuedPerBdv` stores the number of Stalk per BDV for `token`.\n     */\n    function depositWithBDV(\n        address account,\n        address token,\n        int96 stem,\n        uint256 amount,\n        uint256 bdv\n    ) internal returns (uint256 stalk, LibGerminate.Germinate germ) {\n        require(bdv > 0, \"Silo: No Beans under Token.\");\n        AppStorage storage s = LibAppStorage.diamondStorage();\n\n        // determine whether the deposit is odd or even germinating\n        germ = LibGerminate.getSeasonGerminationState();\n\n        // all new deposits will increment total germination.\n        incrementTotalGerminating(token, amount, bdv, germ);\n        \n        addDepositToAccount(\n            account,\n            token,\n            stem,\n            amount,\n            bdv,\n            Transfer.emitTransferSingle\n        );\n\n        stalk = bdv.mul(s.ss[token].stalkIssuedPerBdv);\n    }\n\n    /**\n     * @dev Add `amount` of `token` to a user's Deposit in `stemTipForToken`. Requires a\n     * precalculated `bdv`.\n     *\n     * If a Deposit doesn't yet exist, one is created. Otherwise, the existing\n     * Deposit is updated.\n     *\n     * `amount` & `bdv` are downcasted uint256 -> uint128 to optimize storage cost,\n     * since both values can be packed into one slot.\n     *\n     * Unlike {removeDepositFromAccount}, this function DOES EMIT an\n     * {AddDeposit} event. See {removeDepositFromAccount} for more details.\n     */\n    function addDepositToAccount(\n        address account,\n        address token,\n        int96 stem,\n        uint256 amount,\n        uint256 bdv,\n        Transfer transferType\n    ) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        uint256 depositId = LibBytes.packAddressAndStem(token, stem);\n\n        // add amount and bdv to the deposits.\n        s.a[account].deposits[depositId].amount = s.a[account].deposits[depositId].amount.add(\n            amount.toUint128()\n        );\n        s.a[account].deposits[depositId].bdv = s.a[account].deposits[depositId].bdv.add(\n            bdv.toUint128()\n        );\n\n        // SafeMath unnecessary b/c crateBDV <= type(uint128).max\n        s.a[account].mowStatuses[token].bdv = s.a[account].mowStatuses[token].bdv.add(\n            bdv.toUint128()\n        );\n\n        /**\n         *  {addDepositToAccount} is used for both depositing and transferring deposits.\n         *  In the case of a deposit, only the {TransferSingle} Event needs to be emitted.\n         *  In the case of a transfer, a different {TransferSingle}/{TransferBatch}\n         *  Event is emitted in {TokenSilo._transferDeposit(s)},\n         *  and thus, this event is ommited.\n         */\n        if (transferType == Transfer.emitTransferSingle) {\n            emit TransferSingle(\n                msg.sender, // operator\n                address(0), // from\n                account, // to\n                depositId, // depositID\n                amount // token amount\n            );\n        }\n        emit AddDeposit(account, token, stem, amount, bdv);\n    }\n\n    //////////////////////// REMOVE DEPOSIT ////////////////////////\n\n    /**\n     * @dev Remove `amount` of `token` from a user's Deposit in `stem`.\n     *\n     * A \"Crate\" refers to the existing Deposit in storage at:\n     *  `s.a[account].deposits[token][stem]`\n     *\n     * Partially removing a Deposit should scale its BDV proportionally. For ex.\n     * removing 80% of the tokens from a Deposit should reduce its BDV by 80%.\n     *\n     * During an update, `amount` & `bdv` are cast uint256 -> uint128 to\n     * optimize storage cost, since both values can be packed into one slot.\n     *\n     * This function DOES **NOT** EMIT a {RemoveDeposit} event. This\n     * asymmetry occurs because {removeDepositFromAccount} is called in a loop\n     * in places where multiple deposits are removed simultaneously, including\n     * {TokenSilo-removeDepositsFromAccount} and {TokenSilo-_transferDeposits}.\n     */\n\n    function removeDepositFromAccount(\n        address account,\n        address token,\n        int96 stem,\n        uint256 amount\n    ) internal returns (uint256 crateBDV) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        uint256 depositId = LibBytes.packAddressAndStem(token, stem);\n\n        uint256 crateAmount = s.a[account].deposits[depositId].amount;\n        crateBDV = s.a[account].deposits[depositId].bdv;\n        // if amount is > crateAmount, check if user has a legacy deposit:\n        if (amount > crateAmount) { \n            // get the absolute stem value.\n            uint256 absStem = stem > 0 ? uint256(stem) : uint256(-stem);\n            // only stems with modulo 1e6 can have a legacy deposit.\n            if (absStem.mod(1e6) == 0) {\n                (crateAmount, crateBDV) = migrateLegacyStemDeposit(\n                    account,\n                    token,\n                    stem,\n                    crateAmount,\n                    crateBDV\n                );\n            }\n        }\n        require(amount <= crateAmount, \"Silo: Crate balance too low.\");\n\n        // Partial remove\n        if (amount < crateAmount) {\n            // round up removal of BDV. (x - 1)/y + 1\n            // https://stackoverflow.com/questions/17944\n            uint256 removedBDV = amount.sub(1).mul(crateBDV).div(crateAmount).add(1);\n            uint256 updatedBDV = crateBDV.sub(removedBDV);\n            uint256 updatedAmount = crateAmount.sub(amount);\n\n            // SafeCast unnecessary b/c updatedAmount <= crateAmount and updatedBDV <= crateBDV, \n            // which are both <= type(uint128).max\n            s.a[account].deposits[depositId].amount = updatedAmount.toUint128();\n            s.a[account].deposits[depositId].bdv = updatedBDV.toUint128();\n            \n            s.a[account].mowStatuses[token].bdv = s.a[account].mowStatuses[token].bdv.sub(\n                removedBDV.toUint128()\n            );\n\n            return removedBDV;\n        }\n        // Full remove\n        if (crateAmount > 0) delete s.a[account].deposits[depositId];\n\n        // SafeMath unnecessary b/c crateBDV <= type(uint128).max\n        s.a[account].mowStatuses[token].bdv = s.a[account].mowStatuses[token].bdv.sub(\n            crateBDV.toUint128()\n        );\n    }\n\n    //////////////////////// GETTERS ////////////////////////\n\n    /**\n     * @dev Calculate the BDV (\"Bean Denominated Value\") for `amount` of `token`.\n     *\n     * Makes a call to a BDV function defined in the SiloSettings for this\n     * `token`. See {AppStorage.sol:Storage-SiloSettings} for more information.\n     */\n    function beanDenominatedValue(\n        address token,\n        uint256 amount\n    ) internal view returns (uint256 bdv) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        require(s.ss[token].selector != bytes4(0), \"Silo: Token not whitelisted\");\n\n        (bool success, bytes memory data) = address(this).staticcall(\n            encodeBdvFunction(token, s.ss[token].encodeType, s.ss[token].selector, amount)\n        );\n\n        if (!success) {\n            if (data.length == 0) revert();\n            assembly {\n                revert(add(32, data), mload(data))\n            }\n        }\n\n        assembly {\n            bdv := mload(add(data, add(0x20, 0)))\n        }\n    }\n\n    function encodeBdvFunction(\n        address token,\n        bytes1 encodeType,\n        bytes4 selector,\n        uint256 amount\n    ) internal pure returns (bytes memory callData) {\n        if (encodeType == 0x00) {\n            callData = abi.encodeWithSelector(selector, amount);\n        } else if (encodeType == 0x01) {\n            callData = abi.encodeWithSelector(selector, token, amount);\n        } else {\n            revert(\"Silo: Invalid encodeType\");\n        }\n    }\n\n    /**\n     * @dev Locate the `amount` and `bdv` for a user's Deposit in storage.\n     *\n     * Silo V3 Deposits are stored within each {Account} as a mapping of:\n     *  `uint256 DepositID => { uint128 amount, uint128 bdv }`\n     *  The DepositID is the concatination of the token address and the stem.\n     *\n     * Silo V2 deposits are only usable after a successful migration, see\n     * mowAndMigrate within the Migration facet.\n     *\n     */\n    function getDeposit(\n        address account,\n        address token,\n        int96 stem\n    ) internal view returns (uint256 amount, uint256 bdv) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        uint256 depositId = LibBytes.packAddressAndStem(token, stem);\n        amount = s.a[account].deposits[depositId].amount;\n        bdv = s.a[account].deposits[depositId].bdv;\n    }\n\n    /**\n     * @dev Get the number of Stalk per BDV per Season for a whitelisted token.\n     * 6 decimal precision: 1e10 units = 1 stalk per season\n     */\n    function stalkEarnedPerSeason(address token) internal view returns (uint256) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        return uint256(s.ss[token].stalkEarnedPerSeason);\n    }\n\n    /**\n     * @dev Get the number of Stalk per BDV for a whitelisted token. Formerly just stalk.\n     */\n    function stalkIssuedPerBdv(address token) internal view returns (uint256) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        return uint256(s.ss[token].stalkIssuedPerBdv);\n    }\n\n    /**\n     * @dev returns the cumulative stalk per BDV (stemTip) for a whitelisted token.\n     */\n    function stemTipForToken(\n        address token\n    ) internal view returns (int96 _stemTip) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        // SafeCast unnecessary because all casted variables are types smaller that int96.\n        _stemTip =\n            s.ss[token].milestoneStem +\n            int96(s.ss[token].stalkEarnedPerSeason).mul(\n                int96(s.season.current).sub(int96(s.ss[token].milestoneSeason))\n            );\n    }\n\n    /**\n     * @dev returns the amount of grown stalk a deposit has earned.\n     */\n    function grownStalkForDeposit(\n        address account,\n        address token,\n        int96 stem\n    ) internal view returns (uint grownStalk) {\n        // stemTipForToken(token) > depositGrownStalkPerBdv for all valid Deposits\n        int96 _stemTip = stemTipForToken(token);\n        require(stem <= _stemTip, \"Silo: Invalid Deposit\");\n        // The check in the above line guarantees that subtraction result is positive\n        // and thus the cast to `uint256` is safe.\n        uint deltaStemTip = uint256(_stemTip.sub(stem));\n        // no stalk has grown if the stem is equal to the stemTip.\n        if (deltaStemTip == 0) return 0;\n        (, uint bdv) = getDeposit(account, token, stem);\n\n        grownStalk = deltaStemTip.mul(bdv).div(PRECISION);\n    }\n\n    /**\n     * @dev returns the amount of grown stalk a deposit would have, based on the stem of the deposit.\n     */\n    function calculateStalkFromStemAndBdv(\n        address token,\n        int96 grownStalkIndexOfDeposit,\n        uint256 bdv\n    ) internal view returns (int96 grownStalk) {\n        // current latest grown stalk index\n        int96 _stemTipForToken = stemTipForToken(address(token));\n\n        return _stemTipForToken.sub(grownStalkIndexOfDeposit).mul(toInt96(bdv));\n    }\n\n    /**\n     * @notice returns the grown stalk and germination state of a deposit,\n     * based on the amount of grown stalk it has earned.\n     */\n    function calculateStemForTokenFromGrownStalk(\n        address token,\n        uint256 grownStalk,\n        uint256 bdv\n    ) internal view returns (int96 stem, LibGerminate.Germinate germ) {\n        LibGerminate.GermStem memory germStem = LibGerminate.getGerminatingStem(token);\n        stem = germStem.stemTip.sub(toInt96(grownStalk.mul(PRECISION).div(bdv)));\n        germ = LibGerminate._getGerminationState(stem, germStem);\n    }\n\n    /**\n     * @dev returns the amount of grown stalk a deposit would have, based on the stem of the deposit.\n     * Similar to calculateStalkFromStemAndBdv, but has an additional check to prevent division by 0.\n     */\n    function grownStalkAndBdvToStem(\n        address token,\n        uint256 grownStalk,\n        uint256 bdv\n    ) internal view returns (int96 cumulativeGrownStalk) {\n        // first get current latest grown stalk index\n        int96 _stemTipForToken = stemTipForToken(token);\n        // then calculate how much stalk each individual bdv has grown\n        // there's a > 0 check here, because if you have a small amount of unripe bean deposit, the bdv could\n        // end up rounding to zero, then you get a divide by zero error and can't migrate without losing that deposit\n\n        // prevent divide by zero error\n        int96 grownStalkPerBdv = bdv > 0 ? toInt96(grownStalk.mul(PRECISION).div(bdv)) : 0;\n\n        // subtract from the current latest index, so we get the index the deposit should have happened at\n        return _stemTipForToken.sub(grownStalkPerBdv);\n    }\n\n    /**\n     * @notice internal logic for migrating a legacy deposit.\n     * @dev \n     */\n    function migrateLegacyStemDeposit(\n        address account, \n        address token,\n        int96 newStem,\n        uint256 crateAmount,\n        uint256 crateBdv\n    ) internal returns (uint256, uint256) { \n        AppStorage storage s = LibAppStorage.diamondStorage();\n        // divide the newStem by 1e6 to get the legacy stem.\n        uint256 legacyDepositId = LibBytes.packAddressAndStem(token, newStem.div(1e6));\n        uint256 legacyAmount = s.a[account].legacyV3Deposits[legacyDepositId].amount;\n        uint256 legacyBdv = s.a[account].legacyV3Deposits[legacyDepositId].bdv;\n        crateAmount = crateAmount.add(legacyAmount);\n        crateBdv = crateBdv.add(legacyBdv);\n        delete s.a[account].legacyV3Deposits[legacyDepositId];\n\n        // Emit burn events.\n        emit TransferSingle(\n            msg.sender,\n            account,\n            address(0),\n            legacyDepositId,\n            legacyAmount\n        );\n\n        emit RemoveDeposit(\n            account,\n            token,\n            newStem.div(1e6),\n            legacyAmount,\n            legacyBdv\n        );\n\n        // Emit mint events.\n        emit TransferSingle(\n            msg.sender,\n            address(0),\n            account,\n            LibBytes.packAddressAndStem(token, newStem),\n            legacyAmount\n        );\n\n        emit AddDeposit(\n            account,\n            token,\n            newStem,\n            legacyAmount,\n            legacyBdv\n        );\n\n        return (crateAmount, crateBdv);\n    }\n\n    function toInt96(uint256 value) internal pure returns (int96) {\n        require(value <= uint256(type(int96).max), \"SafeCast: value doesn't fit in an int96\");\n        return int96(value);\n    }\n}\n"
      },
      "contracts/libraries/Silo/LibWhitelistedTokens.sol": {
        "content": "/*\n SPDX-License-Identifier: MIT\n*/\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport {C} from \"../../C.sol\";\nimport {AppStorage, Storage, LibAppStorage} from \"contracts/libraries/LibAppStorage.sol\";\n\n/**\n * @title LibWhitelistedTokens\n * @author Brean, Brendan\n * @notice LibWhitelistedTokens holds different lists of types of Whitelisted Tokens.\n * \n * @dev manages the WhitelistStatuses for all tokens in the Silo in order to track lists.\n * Note: dewhitelisting a token doesn't remove it's WhitelistStatus entirely–It just modifies it.\n * Once a token has no more Deposits in the Silo, it's WhitelistStatus should be removed through calling `removeWhitelistStatus`.\n */\nlibrary LibWhitelistedTokens {\n\n\n    /** \n     * @notice Emitted when a Whitelis Status is added.\n     */\n    event AddWhitelistStatus(\n        address token,\n        uint256 index,\n        bool isWhitelisted,\n        bool isWhitelistedLp,\n        bool isWhitelistedWell\n    );\n\n    /**\n     * @notice Emitted when a Whitelist Status is removed.\n     */\n    event RemoveWhitelistStatus(\n        address token,\n        uint256 index\n    );\n\n    /**\n     * @notice Emitted when a Whitelist Status is updated.\n     */\n    event UpdateWhitelistStatus(\n        address token,\n        uint256 index,\n        bool isWhitelisted,\n        bool isWhitelistedLp,\n        bool isWhitelistedWell\n    );\n\n    /**\n     * @notice Returns all tokens that are currently or previously in the silo, \n     * including Unripe tokens.\n     * @dev includes Dewhitelisted tokens with existing Deposits.\n     */\n    function getSiloTokens() internal view returns (address[] memory tokens) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        uint256 numberOfSiloTokens = s.whitelistStatuses.length;\n\n        tokens = new address[](numberOfSiloTokens);\n\n        for (uint256 i = 0; i < numberOfSiloTokens; i++) {\n            tokens[i] = s.whitelistStatuses[i].token;\n        }\n    }\n\n    /**\n     * @notice Returns the current Whitelisted tokens, including Unripe tokens.\n     */\n    function getWhitelistedTokens() internal view returns (address[] memory tokens) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        uint256 numberOfSiloTokens = s.whitelistStatuses.length;\n        uint256 tokensLength;\n    \n        tokens = new address[](numberOfSiloTokens);\n\n        for (uint256 i = 0; i < numberOfSiloTokens; i++) {\n            if (s.whitelistStatuses[i].isWhitelisted) {\n                tokens[tokensLength++] = s.whitelistStatuses[i].token;\n            }\n        }\n        assembly {\n            mstore(tokens, tokensLength)\n        }\n    }\n\n    /**\n     * @notice Returns the current Whitelisted LP tokens. \n     * @dev Unripe LP is not an LP token.\n     */\n    function getWhitelistedLpTokens() internal view returns (address[] memory tokens) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        uint256 numberOfSiloTokens = s.whitelistStatuses.length;\n        uint256 tokensLength;\n\n        tokens = new address[](numberOfSiloTokens);\n\n        for (uint256 i = 0; i < numberOfSiloTokens; i++) {\n            if (s.whitelistStatuses[i].isWhitelistedLp) {\n                // assembly {\n                //     mstore(tokens, add(mload(tokens), 1))\n                // }\n                tokens[tokensLength++] = s.whitelistStatuses[i].token;\n            }\n        }\n        assembly {\n            mstore(tokens, tokensLength)\n        }\n    }\n\n    /**\n     * @notice Returns the current Whitelisted Well LP tokens.\n     */\n    function getWhitelistedWellLpTokens() internal view returns (address[] memory tokens) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        uint256 numberOfSiloTokens = s.whitelistStatuses.length;\n        uint256 tokensLength;\n\n        tokens = new address[](numberOfSiloTokens);\n\n        for (uint256 i = 0; i < numberOfSiloTokens; i++) {\n            if (s.whitelistStatuses[i].isWhitelistedWell) {\n                tokens[tokensLength++] = s.whitelistStatuses[i].token;\n            }\n        }\n        assembly {\n            mstore(tokens, tokensLength)\n        }\n    }\n\n    /**\n     * @notice Returns the Whitelist statues for all tokens that have been whitelisted and not manually removed.\n     */\n    function getWhitelistedStatuses() internal view returns (Storage.WhitelistStatus[] memory _whitelistStatuses) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        _whitelistStatuses = s.whitelistStatuses;\n    }\n\n    /**\n     * @notice Returns the Whitelist status for a given token.\n     */\n    function getWhitelistedStatus(address token) internal view returns (Storage.WhitelistStatus memory _whitelistStatus) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        uint256 tokenStatusIndex = findWhitelistStatusIndex(token);\n        _whitelistStatus = s.whitelistStatuses[tokenStatusIndex];\n    }\n\n    /**\n     * @notice Adds a Whitelist Status for a given `token`.\n     */\n    function addWhitelistStatus(address token, bool isWhitelisted, bool isWhitelistedLp, bool isWhitelistedWell) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        s.whitelistStatuses.push(Storage.WhitelistStatus(\n            token,\n            isWhitelisted,\n            isWhitelistedLp,\n            isWhitelistedWell\n        ));\n\n        emit AddWhitelistStatus(token, s.whitelistStatuses.length - 1, isWhitelisted, isWhitelistedLp, isWhitelistedWell);\n    }\n\n    /**\n     * @notice Modifies the exisiting Whitelist Status of `token`.\n     */\n    function updateWhitelistStatus(address token, bool isWhitelisted, bool isWhitelistedLp, bool isWhitelistedWell) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        uint256 tokenStatusIndex = findWhitelistStatusIndex(token);\n        s.whitelistStatuses[tokenStatusIndex].isWhitelisted = isWhitelisted;\n        s.whitelistStatuses[tokenStatusIndex].isWhitelistedLp = isWhitelistedLp;\n        s.whitelistStatuses[tokenStatusIndex].isWhitelistedWell = isWhitelistedWell;\n\n        emit UpdateWhitelistStatus(\n            token,\n            tokenStatusIndex,\n            isWhitelisted,\n            isWhitelistedLp,\n            isWhitelistedWell\n        );\n    }\n\n    /**\n     * @notice Removes `token`'s Whitelist Status.\n     */\n    function removeWhitelistStatus(address token) internal {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        uint256 tokenStatusIndex = findWhitelistStatusIndex(token);\n        s.whitelistStatuses[tokenStatusIndex] = s.whitelistStatuses[s.whitelistStatuses.length - 1];\n        s.whitelistStatuses.pop();\n\n        emit RemoveWhitelistStatus(token, tokenStatusIndex);\n    }\n\n    /**\n     * @notice Finds the index of a given `token`'s Whitelist Status.\n     */\n    function findWhitelistStatusIndex(address token) private view returns (uint256) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        uint256 whitelistedStatusLength = s.whitelistStatuses.length;\n        uint256 i;\n        while (s.whitelistStatuses[i].token != token) {\n            i++;\n            if (i >= whitelistedStatusLength) {\n                revert(\"LibWhitelistedTokens: Token not found\");\n            }\n        }\n        return i;\n    }\n\n    /**\n     * @notice checks if a token is whitelisted.\n     * @dev checks whether a token is in the whitelistStatuses array. If it is,\n     * verify whether `isWhitelisted` is set to false.\n     * @param token the token to check.\n     */\n    function checkWhitelisted(address token) internal view returns (bool isWhitelisted, bool previouslyWhitelisted) {\n        AppStorage storage s = LibAppStorage.diamondStorage();\n        uint256 whitelistedStatusLength = s.whitelistStatuses.length;\n        uint256 i;\n        while (s.whitelistStatuses[i].token != token) {\n            i++;\n            if (i >= whitelistedStatusLength) {\n                // if the token does not appear in the array\n                // it has not been whitelisted nor dewhitelisted.\n                return (false, false);\n            }\n        }\n\n        if (s.whitelistStatuses[i].isWhitelisted) {\n            // token is whitelisted.\n            return (true, false);\n        } else {\n            // token has been whitelisted previously.\n            return (false, true);\n        }\n    }\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 100
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}