ETH Price: $3,879.65 (-2.17%)

Contract

0x0d8f6F09a2B806d406d511C113f2Fc3F4D608Fc1
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

Advanced mode:
Parent Transaction Hash Block From To
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
MetadataFacet

Compiler Version
v0.7.6+commit.7338295f

Optimization Enabled:
Yes with 100 runs

Other Settings:
default evmVersion
File 1 of 28 : MetadataFacet.sol
/*
 * SPDX-License-Identifier: MIT
 */

pragma solidity ^0.7.6;
pragma experimental ABIEncoderV2;

import "./MetadataImage.sol";
import {LibBytes} from "contracts/libraries/LibBytes.sol";
import {LibTokenSilo} from "contracts/libraries/Silo/LibTokenSilo.sol";


/**
 * @title MetadataFacet
 * @author Brean
 * @notice MetadataFacet is a contract that provides metadata for beanstalk ERC1155 deposits, 
 * as well as other auxiliary functions related to ERC1155 deposits.
 * 
 * @dev Deposits are represented by a uint256, which is the concatination of the token address and the stem.
 */
contract MetadataFacet is MetadataImage {
    using LibStrings for uint256;
    using LibStrings for int256;

    event URI(string _uri, uint256 indexed _id);

    /**
     * @notice Returns the URI for a given depositId.
     * @param depositId - the id of the deposit
     * @dev the URI is a base64 encoded JSON object that contains the metadata and base64 encoded svg.
     * Deposits are stored as a mapping of a uint256 to a Deposit struct.
     * ERC20 deposits are represented by the concatination of the token address and the stem. (20 + 12 bytes).
     */
    function uri(uint256 depositId) external view returns (string memory) {
        (address token, int96 stem) = LibBytes.unpackAddressAndStem(depositId);
        int96 stemTip = LibTokenSilo.stemTipForToken(token);
        // validate the uri
        // the deposit id must return 
        // 1) a token in the silo whitelist (by checking milestone season)
        // 2) a stem that is less than or equal to the stem tip
        require(s.ss[token].milestoneSeason != 0 && stemTip >= stem, "Silo: metadata does not exist");
        bytes memory attributes = abi.encodePacked(
            ', "attributes": [ { "trait_type": "Token", "value": "', getTokenName(token),
            '"}, { "trait_type": "Token Address", "value": "', LibStrings.toHexString(uint256(token), 20),
            '"}, { "trait_type": "Id", "value": "', depositId.toHexString(32),
            '"}, { "trait_type": "stem", "display_type": "number", "value": ', int256(stem).toString(),
            '}, { "trait_type": "initial stalk per BDV", "display_type": "number", "value": ', uint256(LibTokenSilo.stalkIssuedPerBdv(token)).toString(),
            '}, { "trait_type": "grown stalk per BDV", "display_type": "number", "value": ', uint256(stemTip - stem).toString(),
            '}, { "trait_type": "stalk grown per BDV per season", "display_type": "number", "value": ', uint256(LibTokenSilo.stalkEarnedPerSeason(token)).toString()
        );
        return string(abi.encodePacked("data:application/json;base64,",LibBytes64.encode(abi.encodePacked(
                '{',
                    '"name": "Beanstalk Silo Deposits", "description": "An ERC1155 representing an asset deposited in the Beanstalk Silo. Silo Deposits gain stalk and bean seignorage. ',
                    '\\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."',                    
                    attributes,
                    string(abi.encodePacked(' }], "image": "', imageURI(token, stem, stemTip), '"')),
                '}'
            ))
        ));
    }

    function name() external pure returns (string memory){
        return "Beanstalk Silo Deposits";
    }

    function symbol() external pure returns (string memory){
        return "DEPOSIT";
    }
}

File 2 of 28 : SafeMath.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        uint256 c = a + b;
        if (c < a) return (false, 0);
        return (true, c);
    }

    /**
     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b > a) return (false, 0);
        return (true, a - b);
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) return (true, 0);
        uint256 c = a * b;
        if (c / a != b) return (false, 0);
        return (true, c);
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b == 0) return (false, 0);
        return (true, a / b);
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b == 0) return (false, 0);
        return (true, a % b);
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");
        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b <= a, "SafeMath: subtraction overflow");
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        if (a == 0) return 0;
        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");
        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b > 0, "SafeMath: division by zero");
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b > 0, "SafeMath: modulo by zero");
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        return a - b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryDiv}.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        return a % b;
    }
}

File 3 of 28 : ERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin guidelines: functions revert instead
 * of returning `false` on failure. This behavior is nonetheless conventional
 * and does not conflict with the expectations of ERC20 applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20 {
    using SafeMath for uint256;

    mapping (address => uint256) private _balances;

    mapping (address => mapping (address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;
    uint8 private _decimals;

    /**
     * @dev Sets the values for {name} and {symbol}, initializes {decimals} with
     * a default value of 18.
     *
     * To select a different value for {decimals}, use {_setupDecimals}.
     *
     * All three of these values are immutable: they can only be set once during
     * construction.
     */
    constructor (string memory name_, string memory symbol_) public {
        _name = name_;
        _symbol = symbol_;
        _decimals = 18;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5,05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
     * called.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return _decimals;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `recipient` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * Requirements:
     *
     * - `sender` and `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     * - the caller must have allowance for ``sender``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);
        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
        return true;
    }

    /**
     * @dev Moves tokens `amount` from `sender` to `recipient`.
     *
     * This is internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `sender` cannot be the zero address.
     * - `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     */
    function _transfer(address sender, address recipient, uint256 amount) internal virtual {
        require(sender != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(sender, recipient, amount);

        _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
        _balances[recipient] = _balances[recipient].add(amount);
        emit Transfer(sender, recipient, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply = _totalSupply.add(amount);
        _balances[account] = _balances[account].add(amount);
        emit Transfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
        _totalSupply = _totalSupply.sub(amount);
        emit Transfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Sets {decimals} to a value other than the default one of 18.
     *
     * WARNING: This function should only be called from the constructor. Most
     * applications that interact with token contracts will not expect
     * {decimals} to ever change, and may work incorrectly if it does.
     */
    function _setupDecimals(uint8 decimals_) internal virtual {
        _decimals = decimals_;
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be to transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}

File 4 of 28 : IERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

File 5 of 28 : Context.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with GSN meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address payable) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes memory) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}

File 6 of 28 : Counters.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

import "../math/SafeMath.sol";

/**
 * @title Counters
 * @author Matt Condon (@shrugs)
 * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
 * of elements in a mapping, issuing ERC721 ids, or counting request ids.
 *
 * Include with `using Counters for Counters.Counter;`
 * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
 * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
 * directly accessed.
 */
library Counters {
    using SafeMath for uint256;

    struct Counter {
        // This variable should never be directly accessed by users of the library: interactions must be restricted to
        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
        // this feature: see https://github.com/ethereum/solidity/issues/4637
        uint256 _value; // default: 0
    }

    function current(Counter storage counter) internal view returns (uint256) {
        return counter._value;
    }

    function increment(Counter storage counter) internal {
        // The {SafeMath} overflow check can be skipped here, see the comment at the top
        counter._value += 1;
    }

    function decrement(Counter storage counter) internal {
        counter._value = counter._value.sub(1);
    }
}

File 7 of 28 : SafeCast.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;


/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits.
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128) {
        require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
        return int128(value);
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64) {
        require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
        return int64(value);
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32) {
        require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
        return int32(value);
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16) {
        require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
        return int16(value);
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits.
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8) {
        require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
        return int8(value);
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        require(value < 2**255, "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}

File 8 of 28 : AppStorage.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import "../interfaces/IDiamondCut.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Counters.sol";

/**
 * @title Account
 * @author Publius
 * @notice Stores Farmer-level Beanstalk state.
 * @dev {Account.State} is the primary struct that is referenced from {Storage.State}. 
 * All other structs in {Account} are referenced in {Account.State}. Each unique
 * Ethereum address is a Farmer.
 */
contract Account {
    /**
     * @notice Stores a Farmer's Plots and Pod allowances.
     * @param plots A Farmer's Plots. Maps from Plot index to Pod amount.
     * @param podAllowances An allowance mapping for Pods similar to that of the ERC-20 standard. Maps from spender address to allowance amount.
     */
    struct Field {
        mapping(uint256 => uint256) plots;
        mapping(address => uint256) podAllowances;
    }

    /**
     * @notice Stores a Farmer's Deposits and Seeds per Deposit, and formerly stored Withdrawals.
     * @param withdrawals DEPRECATED: Silo V1 Withdrawals are no longer referenced.
     * @param deposits Unripe Bean/LP Deposits (previously Bean/LP Deposits).
     * @param depositSeeds BDV of Unripe LP Deposits / 4 (previously # of Seeds in corresponding LP Deposit).
     */
    struct AssetSilo {
        mapping(uint32 => uint256) withdrawals;
        mapping(uint32 => uint256) deposits;
        mapping(uint32 => uint256) depositSeeds;
    }

    /**
     * @notice Represents a Deposit of a given Token in the Silo at a given Season.
     * @param amount The amount of Tokens in the Deposit.
     * @param bdv The Bean-denominated value of the total amount of Tokens in the Deposit.
     * @dev `amount` and `bdv` are packed as uint128 to save gas.
     */
    struct Deposit {
        uint128 amount; // ───┐ 16
        uint128 bdv; // ──────┘ 16 (32/32)
    }

    /**
     * @notice Stores a Farmer's Stalk and Seeds balances.
     * @param stalk Balance of the Farmer's Stalk.
     * @param seeds DEPRECATED – Balance of the Farmer's Seeds. Seeds are no longer referenced as of Silo V3.
     */
    struct Silo {
        uint256 stalk;
        uint256 seeds;
    }
    
    /**
     * @notice Stores a Farmer's germinating stalk.
     * @param odd - stalk from assets deposited in odd seasons.
     * @param even - stalk from assets deposited in even seasons.
     */
    struct FarmerGerminatingStalk {
        uint128 odd;
        uint128 even;
    }
    
    /**
     * @notice This struct stores the mow status for each Silo-able token, for each farmer. 
     * This gets updated each time a farmer mows, or adds/removes deposits.
     * @param lastStem The last cumulative grown stalk per bdv index at which the farmer mowed.
     * @param bdv The bdv of all of a farmer's deposits of this token type.
     * 
     */
    struct MowStatus {
        int96 lastStem; // ───┐ 12
        uint128 bdv; // ──────┘ 16 (28/32)
    }

    /**
     * @notice Stores a Farmer's Season of Plenty (SOP) balances.
     * @param roots The number of Roots a Farmer had when it started Raining.
     * @param plentyPerRoot The global Plenty Per Root index at the last time a Farmer updated their Silo.
     * @param plenty The balance of a Farmer's plenty. Plenty can be claimed directly for 3CRV.
     */
    struct SeasonOfPlenty {
        uint256 roots;
        uint256 plentyPerRoot;
        uint256 plenty;
    }
    
    /**
     * @notice Defines the state object for a Farmer.
     * @param field A Farmer's Field storage.
     * @param bean A Farmer's Unripe Bean Deposits only as a result of Replant (previously held the V1 Silo Deposits/Withdrawals for Beans).
     * @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).
     * @param s A Farmer's Silo storage.
     * @param deprecated_votedUntil DEPRECATED – Replant removed on-chain governance including the ability to vote on BIPs.
     * @param lastUpdate The Season in which the Farmer last updated their Silo.
     * @param lastSop The last Season that a SOP occured at the time the Farmer last updated their Silo.
     * @param lastRain The last Season that it started Raining at the time the Farmer last updated their Silo.
     * @param deprecated_deltaRoots DEPRECATED – BIP-39 introduced germination.
     * @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.
     * @param deprecated_proposedUntil DEPRECATED – Replant removed on-chain governance including the ability to propose BIPs.
     * @param deprecated_sop DEPRECATED – Replant reset the Season of Plenty mechanism
     * @param roots A Farmer's Root balance.
     * @param deprecated_wrappedBeans DEPRECATED – Replant generalized Internal Balances. Wrapped Beans are now stored at the AppStorage level.
     * @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.
     * @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.
     * @param sop A Farmer's Season of Plenty storage.
     * @param depositAllowances A mapping of `spender => Silo token address => amount`.
     * @param tokenAllowances Internal balance token allowances.
     * @param depositPermitNonces A Farmer's current deposit permit nonce
     * @param tokenPermitNonces A Farmer's current token permit nonce
     * @param legacyV3Deposits DEPRECATED: Silo V3 deposits. Deprecated in favor of SiloV3.1 mapping from depositId to Deposit.
     * @param mowStatuses A mapping of Silo-able token address to MowStatus.
     * @param isApprovedForAll A mapping of ERC1155 operator to approved status. ERC1155 compatability.
     * @param farmerGerminating A Farmer's germinating stalk. Seperated into odd and even stalk.
     * @param deposits SiloV3.1 deposits. A mapping from depositId to Deposit. SiloV3.1 introduces greater precision for deposits.
     */
    struct State {
        Field field; // A Farmer's Field storage.

        /*
         * @dev (Silo V1) A Farmer's Unripe Bean Deposits only as a result of Replant
         *
         * Previously held the V1 Silo Deposits/Withdrawals for Beans.

         * NOTE: While the Silo V1 format is now deprecated, this storage slot is used for gas
         * efficiency to store Unripe BEAN deposits. See {LibUnripeSilo} for more.
         */
        AssetSilo bean; 

        /*
         * @dev (Silo V1) Unripe LP Deposits as a result of Replant.
         * 
         * Previously held the V1 Silo Deposits/Withdrawals for BEAN:ETH Uniswap v2 LP Tokens.
         * 
         * BEAN:3CRV and BEAN:LUSD tokens prior to Replant were stored in the Silo V2
         * format in the `s.a[account].legacyV2Deposits` mapping.
         *
         * NOTE: While the Silo V1 format is now deprecated, unmigrated Silo V1 deposits are still
         * stored in this storage slot. See {LibUnripeSilo} for more.
         * 
         */
        AssetSilo lp; 

        /*
         * @dev Holds Silo specific state for each account.
         */
        Silo s;
        
        uint32 votedUntil; // DEPRECATED – Replant removed on-chain governance including the ability to vote on BIPs.
        uint32 lastUpdate; // The Season in which the Farmer last updated their Silo.
        uint32 lastSop; // The last Season that a SOP occured at the time the Farmer last updated their Silo.
        uint32 lastRain; // The last Season that it started Raining at the time the Farmer last updated their Silo.
        uint128 deprecated_deltaRoots; // DEPRECATED - BIP-39 introduced germination. 
        SeasonOfPlenty deprecated; // DEPRECATED – Replant reset the Season of Plenty mechanism
        uint256 roots; // A Farmer's Root balance.
        uint256 deprecated_wrappedBeans; // DEPRECATED – Replant generalized Internal Balances. Wrapped Beans are now stored at the AppStorage level.
        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.
        mapping(address => mapping(uint32 => uint256)) withdrawals; // Zero withdraw eliminates a need for withdraw mapping, but is kept for legacy
        SeasonOfPlenty sop; // A Farmer's Season Of Plenty storage.
        mapping(address => mapping(address => uint256)) depositAllowances; // Spender => Silo Token
        mapping(address => mapping(IERC20 => uint256)) tokenAllowances; // Token allowances
        uint256 depositPermitNonces; // A Farmer's current deposit permit nonce
        uint256 tokenPermitNonces; // A Farmer's current token permit nonce
        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.
        mapping(address => MowStatus) mowStatuses; // Store a MowStatus for each Whitelisted Silo token
        mapping(address => bool) isApprovedForAll; // ERC1155 isApprovedForAll mapping 
        
        // Germination
        FarmerGerminatingStalk farmerGerminating; // A Farmer's germinating stalk.

        // Silo v3.1
        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.
    }
}

/**
 * @title Storage
 * @author Publius
 * @notice Stores system-level Beanstalk state.
 */
contract Storage {
    /**
     * @notice DEPRECATED: System-level contract addresses.
     * @dev After Replant, Beanstalk stores Token addresses as constants to save gas.
     */
    struct Contracts {
        address bean;
        address pair;
        address pegPair;
        address weth;
    }

    /**
     * @notice System-level Field state variables.
     * @param soil The number of Soil currently available. Adjusted during {Sun.stepSun}.
     * @param beanSown The number of Bean sown within the current Season. Reset during {Weather.calcCaseId}.
     * @param pods The pod index; the total number of Pods ever minted.
     * @param harvested The harvested index; the total number of Pods that have ever been Harvested.
     * @param harvestable The harvestable index; the total number of Pods that have ever been Harvestable. Included previously Harvested Beans.
     */
    struct Field {
        uint128 soil; // ──────┐ 16
        uint128 beanSown; // ──┘ 16 (32/32)
        uint256 pods;
        uint256 harvested;
        uint256 harvestable;
    }

    /**
     * @notice DEPRECATED: Contained data about each BIP (Beanstalk Improvement Proposal).
     * @dev Replant moved governance off-chain. This struct is left for future reference.
     * 
     */
    struct Bip {
        address proposer; // ───┐ 20
        uint32 start; //        │ 4 (24)
        uint32 period; //       │ 4 (28)
        bool executed; // ──────┘ 1 (29/32)
        int pauseOrUnpause; 
        uint128 timestamp;
        uint256 roots;
        uint256 endTotalRoots;
    }

    /**
     * @notice DEPRECATED: Contained data for the DiamondCut associated with each BIP.
     * @dev Replant moved governance off-chain. This struct is left for future reference.
     * @dev {Storage.DiamondCut} stored DiamondCut-related data for each {Bip}.
     */
    struct DiamondCut {
        IDiamondCut.FacetCut[] diamondCut;
        address initAddress;
        bytes initData;
    }

    /**
     * @notice DEPRECATED: Contained all governance-related data, including a list of BIPs, votes for each BIP, and the DiamondCut needed to execute each BIP.
     * @dev Replant moved governance off-chain. This struct is left for future reference.
     * @dev {Storage.Governance} stored all BIPs and Farmer voting information.
     */
    struct Governance {
        uint32[] activeBips;
        uint32 bipIndex;
        mapping(uint32 => DiamondCut) diamondCuts;
        mapping(uint32 => mapping(address => bool)) voted;
        mapping(uint32 => Bip) bips;
    }

    /**
     * @notice System-level Silo state; contains deposit and withdrawal data for a particular whitelisted Token.
     * @param deposited The total amount of this Token currently Deposited in the Silo.
     * @param depositedBdv The total bdv of this Token currently Deposited in the Silo.
     * @param withdrawn The total amount of this Token currently Withdrawn From the Silo.
     * @dev {Storage.State} contains a mapping from Token address => AssetSilo.
     * Currently, the bdv of deposits are asynchronous, and require an on-chain transaction to update.
     * Thus, the total bdv of deposits cannot be calculated, and must be stored and updated upon a bdv change.
     * 
     * 
     * Note that "Withdrawn" refers to the amount of Tokens that have been Withdrawn
     * but not yet Claimed. This will be removed in a future BIP.
     */
    struct AssetSilo {
        uint128 deposited;
        uint128 depositedBdv;
        uint256 withdrawn;
    }

    /**
     * @notice Whitelist Status a token that has been Whitelisted before.
     * @param token the address of the token.
     * @param a whether the address is whitelisted.
     * @param isWhitelistedLp whether the address is a whitelisted LP token.
     * @param isWhitelistedWell whether the address is a whitelisted Well token.
     */

    struct WhitelistStatus {
        address token;
        bool isWhitelisted;
        bool isWhitelistedLp;
        bool isWhitelistedWell;
    }

    /**
     * @notice System-level Silo state variables.
     * @param stalk The total amount of active Stalk (including Earned Stalk, excluding Grown Stalk).
     * @param deprecated_seeds DEPRECATED: The total amount of active Seeds (excluding Earned Seeds).
     * @dev seeds are no longer used internally. Balance is wiped to 0 from the mayflower update. see {mowAndMigrate}.
     * @param roots The total amount of Roots.
     */
    struct Silo {
        uint256 stalk;
        uint256 deprecated_seeds; 
        uint256 roots;
    }

    /**
     * @notice System-level Curve Metapool Oracle state variables.
     * @param initialized True if the Oracle has been initialzed. It needs to be initialized on Deployment and re-initialized each Unpause.
     * @param startSeason The Season the Oracle started minting. Used to ramp up delta b when oracle is first added.
     * @param balances The cumulative reserve balances of the pool at the start of the Season (used for computing time weighted average delta b).
     * @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.
     * @dev Currently refers to the time weighted average deltaB calculated from the BEAN:3CRV pool.
     */
    struct CurveMetapoolOracle {
        bool initialized; // ────┐ 1
        uint32 startSeason; // ──┘ 4 (5/32)
        uint256[2] balances;
        uint256 timestamp;
    }

    /**
     * @notice System-level Rain balances. Rain occurs when P > 1 and the Pod Rate Excessively Low.
     * @dev The `raining` storage variable is stored in the Season section for a gas efficient read operation.
     * @param deprecated Previously held Rain start and Rain status variables. Now moved to Season struct for gas efficiency.
     * @param pods The number of Pods when it last started Raining.
     * @param roots The number of Roots when it last started Raining.
     */
    struct Rain {
        uint256 deprecated;
        uint256 pods;
        uint256 roots;
    }

    /**
     * @notice System-level Season state variables.
     * @param current The current Season in Beanstalk.
     * @param lastSop The Season in which the most recent consecutive series of Seasons of Plenty started.
     * @param withdrawSeasons The number of Seasons required to Withdraw a Deposit.
     * @param lastSopSeason The Season in which the most recent consecutive series of Seasons of Plenty ended.
     * @param rainStart Stores the most recent Season in which Rain started.
     * @param raining True if it is Raining (P > 1, Pod Rate Excessively Low).
     * @param fertilizing True if Beanstalk has Fertilizer left to be paid off.
     * @param sunriseBlock The block of the start of the current Season.
     * @param abovePeg Boolean indicating whether the previous Season was above or below peg.
     * @param stemStartSeason // season in which the stem storage method was introduced.
     * @param stemScaleSeason // season in which the stem v1.1 was introduced, where stems are not truncated anymore.
     * @param beanEthStartMintingSeason // Season to start minting in Bean:Eth pool after migrating liquidity out of the pool to protect against Pump failure.
     * This allows for greater precision of stems, and requires a soft migration (see {LibTokenSilo.removeDepositFromAccount})
     * @param start The timestamp of the Beanstalk deployment rounded down to the nearest hour.
     * @param period The length of each season in Beanstalk in seconds.
     * @param timestamp The timestamp of the start of the current Season.
     */
    struct Season {
        uint32 current; // ─────────────────┐ 4  
        uint32 lastSop; //                  │ 4 (8)
        uint8 withdrawSeasons; //           │ 1 (9)
        uint32 lastSopSeason; //            │ 4 (13)
        uint32 rainStart; //                │ 4 (17)
        bool raining; //                    │ 1 (18)
        bool fertilizing; //                │ 1 (19)
        uint32 sunriseBlock; //             │ 4 (23)
        bool abovePeg; //                   | 1 (24)
        uint16 stemStartSeason; //          | 2 (26)
        uint16 stemScaleSeason; //          | 2 (28/32)
        uint32 beanEthStartMintingSeason; //┘ 4 (32/32) NOTE: Reset and delete after Bean:wStEth migration has been completed.
        uint256 start;
        uint256 period;
        uint256 timestamp;
    }

    /**
     * @notice System-level Weather state variables.
     * @param deprecated 2 slots that were previously used.
     * @param lastDSoil Delta Soil; the number of Soil purchased last Season.
     * @param lastSowTime The number of seconds it for Soil to sell out last Season.
     * @param thisSowTime The number of seconds it for Soil to sell out this Season.
     * @param t The Temperature; the maximum interest rate during the current Season for sowing Beans in Soil. Adjusted each Season.
     */
    struct Weather {
        uint256[2] deprecated;
        uint128 lastDSoil;  // ───┐ 16 (16)
        uint32 lastSowTime; //    │ 4  (20)
        uint32 thisSowTime; //    │ 4  (24)
        uint32 t; // ─────────────┘ 4  (28/32)
    }

    /**
     * @notice Describes a Fundraiser.
     * @param payee The address to be paid after the Fundraiser has been fully funded.
     * @param token The token address that used to raise funds for the Fundraiser.
     * @param total The total number of Tokens that need to be raised to complete the Fundraiser.
     * @param remaining The remaining number of Tokens that need to to complete the Fundraiser.
     * @param start The timestamp at which the Fundraiser started (Fundraisers cannot be started and funded in the same block).
     */
    struct Fundraiser {
        address payee;
        address token;
        uint256 total;
        uint256 remaining;
        uint256 start;
    }

    /**
     * @notice Describes the settings for each Token that is Whitelisted in the Silo.
     * @param selector The encoded BDV function selector for the token that pertains to 
     * an external view Beanstalk function with the following signature:
     * ```
     * function tokenToBdv(uint256 amount) external view returns (uint256);
     * ```
     * It is called by `LibTokenSilo` through the use of `delegatecall`
     * to calculate a token's BDV at the time of Deposit.
     * @param stalkEarnedPerSeason represents how much Stalk one BDV of the underlying deposited token
     * grows each season. In the past, this was represented by seeds. This is stored as 1e6, plus stalk is stored
     * as 1e10, so 1 legacy seed would be 1e6 * 1e10.
     * @param stalkIssuedPerBdv The Stalk Per BDV that the Silo grants in exchange for Depositing this Token.
     * previously called stalk.
     * @param milestoneSeason The last season in which the stalkEarnedPerSeason for this token was updated.
     * @param milestoneStem The cumulative amount of grown stalk per BDV for this token at the last stalkEarnedPerSeason update.
     * @param encodeType determine the encoding type of the selector.
     * a encodeType of 0x00 means the selector takes an input amount.
     * 0x01 means the selector takes an input amount and a token.
     * @param gpSelector The encoded gaugePoint function selector for the token that pertains to 
     * an external view Beanstalk function with the following signature:
     * ```
     * function gaugePoints(
     *  uint256 currentGaugePoints,
     *  uint256 optimalPercentDepositedBdv,
     *  uint256 percentOfDepositedBdv
     *  ) external view returns (uint256);
     * ```
     * @param lwSelector The encoded liquidityWeight function selector for the token that pertains to 
     * an external view Beanstalk function with the following signature `function liquidityWeight()`
     * @param optimalPercentDepositedBdv The target percentage of the total LP deposited BDV for this token. 6 decimal precision.
     * @param gaugePoints the amount of Gauge points this LP token has in the LP Gauge. Only used for LP whitelisted assets.
     * GaugePoints has 18 decimal point precision (1 Gauge point = 1e18).

     * @dev A Token is considered Whitelisted if there exists a non-zero {SiloSettings} selector.
     */
    struct SiloSettings {
        bytes4 selector; // ────────────────────┐ 4
        uint32 stalkEarnedPerSeason; //         │ 4  (8)
        uint32 stalkIssuedPerBdv; //            │ 4  (12)
        uint32 milestoneSeason; //              │ 4  (16)
        int96 milestoneStem; //                 │ 12 (28)
        bytes1 encodeType; //                   │ 1  (29)
        int24 deltaStalkEarnedPerSeason; // ────┘ 3  (32)
        bytes4 gpSelector; //    ────────────────┐ 4  
        bytes4 lwSelector; //                    │ 4  (8)
        uint128 gaugePoints; //                  │ 16 (24)
        uint64 optimalPercentDepositedBdv; //  ──┘ 8  (32)
    }

    /**
     * @notice Describes the settings for each Unripe Token in Beanstalk.
     * @param underlyingToken The address of the Token underlying the Unripe Token.
     * @param balanceOfUnderlying The number of Tokens underlying the Unripe Tokens (redemption pool).
     * @param merkleRoot The Merkle Root used to validate a claim of Unripe Tokens.
     * @dev An Unripe Token is a vesting Token that is redeemable for a a pro rata share
     * of the `balanceOfUnderlying`, subject to a penalty based on the percent of
     * Unfertilized Beans paid back.
     * 
     * There were two Unripe Tokens added at Replant: 
     *  - Unripe Bean, with its `underlyingToken` as BEAN;
     *  - Unripe LP, with its `underlyingToken` as BEAN:3CRV LP.
     * 
     * Unripe Tokens are initially distributed through the use of a `merkleRoot`.
     * 
     * The existence of a non-zero {UnripeSettings} implies that a Token is an Unripe Token.
     */
    struct UnripeSettings {
        address underlyingToken;
        uint256 balanceOfUnderlying;
        bytes32 merkleRoot;
    }

    /**
     * @notice System level variables used in the seed Gauge System.
     * @param averageGrownStalkPerBdvPerSeason The average Grown Stalk Per BDV 
     * that beanstalk issues each season.
     * @param beanToMaxLpGpPerBdvRatio a scalar of the gauge points(GP) per bdv 
     * issued to the largest LP share and Bean. 6 decimal precision.
     * @dev a beanToMaxLpGpPerBdvRatio of 0 means LP should be incentivized the most,
     * and that beans will have the minimum seeds ratio. see {LibGauge.getBeanToMaxLpGpPerBdvRatioScaled}
     */
    struct SeedGauge {
        uint128 averageGrownStalkPerBdvPerSeason;
        uint128 beanToMaxLpGpPerBdvRatio;
    }

    /**
     * @notice Stores the twaReserves for each well during the sunrise function.
     */
    struct TwaReserves {
        uint128 reserve0;
        uint128 reserve1;
    }

    /**
     * @notice Stores the total germination amounts for each whitelisted token.
     */
    struct Deposited {
        uint128 amount;
        uint128 bdv;
    }

    /** 
     * @notice Stores the system level germination data.
     */
    struct TotalGerminating {
        mapping(address => Deposited) deposited;
    }

    struct Sr {
	    uint128 stalk;
	    uint128 roots;
    }
}

/**
 * @title AppStorage
 * @author Publius
 * @notice Defines the state object for Beanstalk.
 * @param deprecated_index DEPRECATED: Was the index of the BEAN token in the BEAN:ETH Uniswap V2 pool.
 * @param deprecated_cases DEPRECATED: The 24 Weather cases used in cases V1 (array has 32 items, but caseId = 3 (mod 4) are not cases)
 * @param paused True if Beanstalk is Paused.
 * @param pausedAt The timestamp at which Beanstalk was last paused.
 * @param season Storage.Season
 * @param c Storage.Contracts
 * @param f Storage.Field
 * @param g Storage.Governance
 * @param co Storage.CurveMetapoolOracle
 * @param r Storage.Rain
 * @param s Storage.Silo
 * @param reentrantStatus An intra-transaction state variable to protect against reentrance.
 * @param w Storage.Weather
 * @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.
 * @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.
 * @param a mapping (address => Account.State)
 * @param deprecated_bip0Start DEPRECATED - bip0Start was used to aid in a migration that occured alongside BIP-0.
 * @param deprecated_hotFix3Start DEPRECATED - hotFix3Start was used to aid in a migration that occured alongside HOTFIX-3.
 * @param fundraisers A mapping from Fundraiser ID to Storage.Fundraiser.
 * @param fundraiserIndex The number of Fundraisers that have occured.
 * @param deprecated_isBudget DEPRECATED - Budget Facet was removed in BIP-14. 
 * @param podListings A mapping from Plot Index to the hash of the Pod Listing.
 * @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.
 * @param siloBalances A mapping from Token address to Silo Balance storage (amount deposited and withdrawn).
 * @param ss A mapping from Token address to Silo Settings for each Whitelisted Token. If a non-zero storage exists, a Token is whitelisted.
 * @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.
 * @param deprecated_newEarnedStalk the amount of earned stalk issued this season. Since 1 stalk = 1 bean, it represents the earned beans as well.
 * @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.
 * @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.
 * @param unripeClaimed True if a Farmer has Claimed an Unripe Token. A mapping from Farmer to Unripe Token to its Claim status.
 * @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.
 * @param fertilizer A mapping from Fertilizer Id to the supply of Fertilizer for each Id.
 * @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.
 * @param activeFertilizer The number of active Fertilizer.
 * @param fertilizedIndex The total number of Fertilizer Beans.
 * @param unfertilizedIndex The total number of Unfertilized Beans ever.
 * @param fFirst The lowest active Fertilizer Id (start of linked list that is stored by nextFid). 
 * @param fLast The highest active Fertilizer Id (end of linked list that is stored by nextFid). 
 * @param bpf The cumulative Beans Per Fertilizer (bfp) minted over all Season.
 * @param deprecated_vestingPeriodRoots deprecated - removed in BIP-39 in favor of germination.
 * @param recapitalized The number of USDC that has been recapitalized in the Barn Raise.
 * @param isFarm Stores whether the function is wrapped in the `farm` function (1 if not, 2 if it is).
 * @param ownerCandidate Stores a candidate address to transfer ownership to. The owner must claim the ownership transfer.
 * @param wellOracleSnapshots A mapping from Well Oracle address to the Well Oracle Snapshot.
 * @param deprecated_beanEthPrice DEPRECATED - The price of bean:eth, originally used to calculate the incentive reward. Deprecated in favor of calculating using twaReserves.
 * @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.
 * @param migratedBdvs Stores the total migrated BDV since the implementation of the migrated BDV counter. See {LibLegacyTokenSilo.incrementMigratedBdv} for more info.
 * @param usdEthPrice  Stores the usdEthPrice during the sunrise() function. Returns 1 otherwise.
 * @param seedGauge Stores the seedGauge.
 * @param casesV2 Stores the 144 Weather and seedGauge cases.
 * @param oddGerminating Stores germinating data during odd seasons.
 * @param evenGerminating Stores germinating data during even seasons.
 * @param whitelistedStatues Stores a list of Whitelist Statues for all tokens that have been Whitelisted and have not had their Whitelist Status manually removed.
 * @param sopWell Stores the well that will be used upon a SOP. Unintialized until a SOP occurs, and is kept constant afterwards.
 * @param barnRaiseWell Stores the well that the Barn Raise adds liquidity to.
 */
struct AppStorage {
    uint8 deprecated_index;
    int8[32] deprecated_cases; 
    bool paused; // ────────┐ 1 
    uint128 pausedAt; // ───┘ 16 (17/32)
    Storage.Season season;
    Storage.Contracts c;
    Storage.Field f;
    Storage.Governance g;
    Storage.CurveMetapoolOracle co;
    Storage.Rain r;
    Storage.Silo s;
    uint256 reentrantStatus;
    Storage.Weather w;

    uint256 earnedBeans;
    uint256[14] deprecated;
    mapping (address => Account.State) a;
    uint32 deprecated_bip0Start; // ─────┐ 4
    uint32 deprecated_hotFix3Start; // ──┘ 4 (8/32)
    mapping (uint32 => Storage.Fundraiser) fundraisers;
    uint32 fundraiserIndex; // 4 (4/32)
    mapping (address => bool) deprecated_isBudget;
    mapping(uint256 => bytes32) podListings;
    mapping(bytes32 => uint256) podOrders;
    mapping(address => Storage.AssetSilo) siloBalances;
    mapping(address => Storage.SiloSettings) ss;
    uint256[2] deprecated2;
    uint128 deprecated_newEarnedStalk; // ──────┐ 16
    uint128 deprecated_vestingPeriodRoots; // ──┘ 16 (32/32)
    mapping (uint32 => uint256) sops;

    // Internal Balances
    mapping(address => mapping(IERC20 => uint256)) internalTokenBalance;

    // Unripe
    mapping(address => mapping(address => bool)) unripeClaimed;
    mapping(address => Storage.UnripeSettings) u;

    // Fertilizer
    mapping(uint128 => uint256) fertilizer;
    mapping(uint128 => uint128) nextFid;
    uint256 activeFertilizer;
    uint256 fertilizedIndex;
    uint256 unfertilizedIndex;
    uint128 fFirst;
    uint128 fLast;
    uint128 bpf;
    uint256 recapitalized;

    // Farm
    uint256 isFarm;

    // Ownership
    address ownerCandidate;

    // Well
    mapping(address => bytes) wellOracleSnapshots;

    uint256 deprecated_beanEthPrice;

    // Silo V3 BDV Migration
    mapping(address => uint256) migratedBdvs;

    // Well/Curve + USD Price Oracle
    mapping(address => Storage.TwaReserves) twaReserves;
    mapping(address => uint256) usdTokenPrice;

    // Seed Gauge
    Storage.SeedGauge seedGauge;
    bytes32[144] casesV2;

    // Germination
    Storage.TotalGerminating oddGerminating;
    Storage.TotalGerminating evenGerminating;

    // mapping from season => unclaimed germinating stalk and roots 
    mapping(uint32 => Storage.Sr) unclaimedGerminating;

    Storage.WhitelistStatus[] whitelistStatuses;

    address sopWell;
}

File 9 of 28 : MetadataImage.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.6;
import "../AppStorage.sol";
import {LibBytes64} from "contracts/libraries/LibBytes64.sol";
import {LibStrings} from "contracts/libraries/LibStrings.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {C} from "../../C.sol";


/**
 * @title MetadataImage
 * @author Brean
 * @notice Contains image metadata for ERC1155 deposits.
 * @dev fully on-chain generated SVG.
 */

contract MetadataImage {
    AppStorage internal s;

    using LibStrings for uint256;
    using LibStrings for int256;
    using SafeMath for uint256;

    string constant LEAF_COLOR_0 = '#A8C83A';
    string constant LEAF_COLOR_1 = '#89A62F';
    uint256 constant NUM_PLOTS = 21;
    uint256 constant STALK_GROWTH = 2e8;

    function imageURI(address token, int96 stem, int96 stemTip) public view returns (string memory) {
        return string(
            abi.encodePacked(
                "data:image/svg+xml;base64,", 
                LibBytes64.encode(bytes(generateImage(token, stem, stemTip)))
            )
        );
    }

    function generateImage(address token, int96 stem, int96 stemTip) internal view returns (string memory) {
        int96 grownStalkPerBdv = stemTip - stem;
        return string(
            abi.encodePacked(
                '<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">',
                defs(grownStalkPerBdv),
                back(),
                printPlots(grownStalkPerBdv),
                blackBars(token, stem),
                '</svg>'
            )
        );
    }

    function back() internal pure returns(string memory) {
        return string(abi.encodePacked(
            '<rect width="255" height="350" rx="10" fill="',
            '#253326',
            '"/>'
        ));
    }

    function defs(int96 stemTip) internal pure returns(string memory) {
        (uint256 sprouts,) = getNumStemsAndPlots(stemTip);
        uint256 sproutsInFinalRow = sprouts.mod(4);
        return string(abi.encodePacked(
            '<defs>',
            plot(),
            fullLeafPlot(),
            emptyPlot(),
            partialLeafRow(sproutsInFinalRow),
            partialLeafPlot(stemTip),
            leaf(),
            silo(),
            fullLeafRow(),
            '</defs>'
        ));
    }

    function mask() internal pure returns (string memory) {
        return string(abi.encodePacked(
            '<clipPath id="borderMask">',
            border(),
            '</clipPath>'
        ));
    }

    function border() internal pure returns (string memory) {
        return '<rect x="8" y="8" width="240" height="335" rx="6" stroke="#9BCAA0" stroke-width="2" fill="none"/>';
    }

    function fullLeafRow() internal pure returns (string memory) {
        return string(abi.encodePacked(
            '<g id="leafRow">',
            '<use xlink:href="#leaf" x="0" y="0"/>',
            '<use xlink:href="#leaf" x="-12" y="-7"/>',
            '<use xlink:href="#leaf" x="-24" y="-14"/>',
            '<use xlink:href="#leaf" x="-36" y="-21"/>',
            '</g>'
        ));
    }

    function partialLeafRow(uint256 n) internal pure returns (string memory) {
        if (n == 0) { 
            return string(abi.encodePacked(
                '<g id="partialLeafRow">',
                '</g>'
            ));
        }
        if (n == 1) { 
            return string(abi.encodePacked(
                '<g id="partialLeafRow">',
                '<use xlink:href="#leaf" x="0" y="0"/>',
                '</g>'
            ));
        }
        if (n == 2) { 
            return string(abi.encodePacked(
                '<g id="partialLeafRow">',
                '<use xlink:href="#leaf" x="0" y="0"/>',
                '<use xlink:href="#leaf" x="-12" y="-7"/>',
                '</g>'
            ));
        }
        if (n == 3) { 
            return string(abi.encodePacked(
                '<g id="partialLeafRow">',
                '<use xlink:href="#leaf" x="0" y="0"/>',
                '<use xlink:href="#leaf" x="-12" y="-7"/>',
                '<use xlink:href="#leaf" x="-24" y="-14"/>',
                '</g>'
            ));
        } else {
            return string(abi.encodePacked(
                '<g id="partialLeafRow">',
                '<use xlink:href="#leaf" x="0" y="0"/>',
                '<use xlink:href="#leaf" x="-12" y="-7"/>',
                '<use xlink:href="#leaf" x="-24" y="-14"/>',
                '<use xlink:href="#leaf" x="-36" y="-21"/>',
                '</g>'
            ));
        }
       
    }


    function fullLeafPlot() internal pure returns (string memory) {
        return string(abi.encodePacked(
            '<g id="fullLeafPlot">',
            useAssetTransform('plot',-35,0),
            useAssetTransformFill('leafRow',-35,0, LEAF_COLOR_0),
            useAssetTransformFill('leafRow',-47,7, LEAF_COLOR_1),
            useAssetTransformFill('leafRow',-60,14, LEAF_COLOR_0),
            useAssetTransformFill('leafRow',-73,21, LEAF_COLOR_1),
            '</g>'
        ));
    }

    function emptyPlot() internal pure returns (string memory) {
        return string(abi.encodePacked(
            '<g id="emptyPlot">',
            useAssetTransform('plot',-35,0),
            '</g>'
        ));
    }

    function partialLeafPlot(int96 stalkPerBDV) internal pure returns (string memory _plot) {
        uint256 totalSprouts = uint256(stalkPerBDV).div(STALK_GROWTH).add(16);
        uint256 numRows = uint256(totalSprouts).div(4).mod(4);
        uint256 numSprouts = uint256(totalSprouts).mod(4);
        if (numRows == 0) {
            if (numSprouts > 0) {
                _plot = string(abi.encodePacked(
                    '<g id="partialLeafPlot">',
                    useAssetTransform('plot',-35,0),
                    useAssetTransformFill('partialLeafRow',-35,0, LEAF_COLOR_0),
                    '</g>'
                ));
            } else {
                _plot = string(abi.encodePacked(
                    '<g id="partialLeafPlot">',
                    threeLeafRows(),
                    useAssetTransformFill('leafRow',-73,21, LEAF_COLOR_1),
                    '</g>'
                ));
            }
        }
        if (numRows == 1) {
            if (numSprouts > 0) {
                _plot = string(abi.encodePacked(
                    '<g id="partialLeafPlot">',
                    oneLeafRow(),
                    useAssetTransformFill('partialLeafRow',-47,7, LEAF_COLOR_1),
                    '</g>'
                ));
            } else {
                _plot = string(abi.encodePacked(
                    '<g id="partialLeafPlot">',
                    oneLeafRow(),
                    '</g>'
                ));
            }
        }
        if (numRows == 2) {
            if (numSprouts > 0) {
                _plot = string(abi.encodePacked(
                    '<g id="partialLeafPlot">',
                    twoLeafRows(),
                    useAssetTransformFill('partialLeafRow',-60,14, LEAF_COLOR_0),
                    '</g>'
                ));
            } else {
                _plot = string(abi.encodePacked(
                    '<g id="partialLeafPlot">',
                    twoLeafRows(),
                    '</g>'
                ));
            }
            
        }
        if (numRows == 3) {
            if (numSprouts > 0) {
                _plot = string(abi.encodePacked(
                    '<g id="partialLeafPlot">',
                    threeLeafRows(),
                    useAssetTransformFill('partialLeafRow',-73,21, LEAF_COLOR_1),
                    '</g>'
                ));

            } else {
                _plot = string(abi.encodePacked(
                    '<g id="partialLeafPlot">',
                    threeLeafRows(),
                    '</g>'
                ));
            }
        }
    }

    function printPlots(int96 stalkPerBDV) internal pure returns (string memory) {
        return string(abi.encodePacked(
            '<use xlink:href="#silo" x="99" y="55"/><g id="allPlot" clip-path="url(#borderMask)">',
                plotLogic(stalkPerBDV),
            '</g>'
        ));
    }

    function plotLogic(int96 stalkPerBDV) internal pure returns (string memory) {

        int256[2][21] memory XYPLOT = [

        [int256(-69),-164], // 20
        [int256(69),-164], // 19

        [int256(0),-124], // 13
        [int256(138),-124], // 18
        [int256(-138),-124], // 21

        [int256(-69),-84], // 14
        [int256(69),-84], // 12

        [int256(-138),-44], // 15
        [int256(0),-44], // 5
        [int256(138),-44], // 11

        [int256(-69),-4], // 6
        [int256(69),-4], // 4

        [int256(-138),36], // 7
        [int256(138),36], // 3

        [int256(-69),76], // 8 
        [int256(69),76], // 2

        [int256(-138),116], // 16
        [int256(0),116], // 1
        [int256(138),116], // 10
            
        [int256(69),156], // 9
        [int256(-69),156] // 17
        
        ];
        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];

        bytes memory _plot;

        (, uint256 numPlotsToFill) = getNumStemsAndPlots(stalkPerBDV);

        // first plot should always be planted fully, and every 2% stalk adds a sprout to the next plot.
        for(uint256 i = 0; i < NUM_PLOTS; ++i) {
            uint256 plotNo = order[i];
            if (plotNo < numPlotsToFill) {
                _plot = abi.encodePacked(
                    _plot,
                    useAsset(
                        'fullLeafPlot',
                        XYPLOT[i][0],
                        XYPLOT[i][1]
                    )
                );
            } else if (plotNo == numPlotsToFill) {
                if (numPlotsToFill == 1) {
                    _plot = abi.encodePacked(
                    _plot,
                    useAsset(
                        'fullLeafPlot',
                        XYPLOT[i][0],
                        XYPLOT[i][1]
                    ));
                } else {
                    _plot = abi.encodePacked(
                    _plot,
                    useAsset(
                        'partialLeafPlot',
                        XYPLOT[i][0],
                        XYPLOT[i][1]
                    )
                );
                }
                
            } else {
                _plot = abi.encodePacked(
                    _plot,
                    useAsset(
                        'emptyPlot',
                        XYPLOT[i][0],
                        XYPLOT[i][1]
                    )
                );
            }
            if (i == 11) {
                _plot= abi.encodePacked(
                    _plot,
                    '<use xlink:href="#silo" x="47" y="55" transform="scale(1.7)"/>'
                );
            }
        }
        return string(_plot);
    }

    function useAsset(string memory assetName, int256 x, int256 y) internal pure returns (string memory) { 
        return string(abi.encodePacked(
            '<use xlink:href="#',
            assetName,
            '" x="',
            intToStr(x),
            '" y="',
            intToStr(y),
            '" />'
        ));
    }

    function useAssetFill(string memory assetName, int256 x, int256 y, string memory color) internal pure returns (string memory) { 
        return string(abi.encodePacked(
            '<use xlink:href="#',
            assetName,
            '" x="',
            intToStr(x),
            '" y="',
            intToStr(y),
            '" fill="',
            color,
            '" />'
        ));
    }

    function plot() internal pure returns (string memory) {
        return string(
            abi.encodePacked(
                '<g id="plot">',
                '<path d="M79.5728 129.265L127.469 156.833L175.443 129.245L127.469 101.697L79.5728 129.265Z" fill="#944A27"/>',
                '<path d="M79.5332 133.426L79.5727 129.265L127.469 156.833L127.507 160.908L79.5332 133.426Z" fill="#75391F"/>',
                '<path d="M175.467 133.4L175.443 129.245L127.469 156.833L127.507 160.908L175.467 133.4Z" fill="#67331E"/>',
                "</g>"
            )
        );
    }

    function leaf() internal pure returns (string memory) { 
        return string(
            abi.encodePacked(
                '<g id="leaf">',
                '<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"/>',
                '</g>'
            )
        );
    }

    function silo() internal pure returns (string memory) {
        return string(
            abi.encodePacked(
                '<g id="silo">',
                '<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"/>',
                '<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"/>',
                '<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"/>',
                '<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"/>',
                '<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"/>',
                '<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"/>',
                '<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"/>',
                '<path d="m33.092 49.441-6.381 15.211s-6.078-11.159 6.381-15.21Z" fill="#8E8E8E"/>',
                '<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"/>'
                "</g>"
            )
        );
    }

    function useAssetTransform(string memory assetName, int256 x, int256 y) internal pure returns (string memory) { 
        return string(abi.encodePacked(
            '<use xlink:href="#',
            assetName,
            '" x="',
            intToStr(x),
            '" y="',
            intToStr(y),
            '" transform="scale(1.4)"/>'
        ));
    }

    function useAssetTransformFill(string memory assetName, int256 x, int256 y, string memory color) internal pure returns (string memory) { 
        return string(abi.encodePacked(
            '<use xlink:href="#',
            assetName,
            '" x="',
            intToStr(x),
            '" y="',
            intToStr(y),
            '" fill="',
            color,
            '" transform="scale(1.4)"/>'
        ));
    }

    function threeLeafRows() internal pure returns (string memory) {
        return string(
            abi.encodePacked(
                twoLeafRows(),
                useAssetTransformFill('leafRow',-60,14, LEAF_COLOR_0)
            )
        );
    }

    function twoLeafRows() internal pure returns (string memory) {
        return string(
            abi.encodePacked(
                oneLeafRow(),
                useAssetTransformFill('leafRow',-47,7, LEAF_COLOR_1)
            )
        );
    }

    function oneLeafRow() internal pure returns(string memory) {
        return string(
            abi.encodePacked(
                useAssetTransform('plot',-35,0),
                useAssetTransformFill('leafRow',-35,0, LEAF_COLOR_0)
            )
        );
    }

    function blackBars(address token, int96 stem) internal view returns(string memory) {
        return string(
            abi.encodePacked(
                '<rect x="0" y="0" width="255" height="20" rx="5" fill="#242424"/>',
                tokenName(token),
                '<rect x="0" y="330" width="255" height="20" rx="5" fill="#242424"/>',
                movingTokenAddress(token),
                '<text x="245" y="14.5" font-size="12" fill="White" text-anchor="end" font-family="futura">Stem: ',
                sciNotation(stem),
                '</text>'
            )
        );
    }

    function sciNotation(int96 stem) internal pure returns (string memory) {
        if (stem >= 0) {
            // if stem is greater than 1e5, use scientific notation
            if (stem > 100_000) {
                return powerOfTen(uint256(stem));
            } else {
                return uint256(stem).toString();
            }
        } else {
            // if stem is less than -1e5, use scientific notation
            if (-stem > 100_000) {
                return string(abi.encodePacked("-", powerOfTen(uint256(-stem))));
            } else {
                return int256(stem).toString();
            }
        }
    }

    function powerOfTen(uint256 stem) internal pure returns (string memory) {
        // silo v3.1 increased the precision of stems by 1e6. 
        // we truncate the stem by 6 decimal places in order to support a wider range of stems.
        // the inaccuracy is acceptable given the stem is only used for cosmetic reasons. 
        stem = stem / 1e6;
        // if else ladder to determine how many digits to show.
        if (stem < 1e6) {
            return stemDecimals(stem, 5);
        } else if (stem < 1e7) {
            return stemDecimals(stem, 6);
        } else if (stem < 1e8) {
            return stemDecimals(stem, 7);
        } else if (stem < 1e9) {
            return stemDecimals(stem, 8);
        } else if (stem < 1e10) {
            return stemDecimals(stem, 9);
        } else if (stem < 1e11) {
            return stemDecimals(stem, 10);
        } else if (stem < 1e12) {
            return stemDecimals(stem, 11);
        } else if (stem < 1e13) {
            return stemDecimals(stem, 12);
        } else if (stem < 1e14) {
            return stemDecimals(stem, 13);
        } else if (stem < 1e15) {
            return stemDecimals(stem, 14);
        } else if (stem < 1e16) {
            return stemDecimals(stem, 15);
        } else if (stem < 1e17) {
            return stemDecimals(stem, 16);
        } else if (stem < 1e18) {
            return stemDecimals(stem, 17);
        } else if (stem < 1e19) {
            return stemDecimals(stem, 18);
        } else if (stem < 1e20) {
            return stemDecimals(stem, 19);
        } else if (stem < 1e21) {
            return stemDecimals(stem, 20);
        } else if (stem < 1e22) {
            return stemDecimals(stem, 21);
        } else if (stem < 1e23) {
            return stemDecimals(stem, 22);
        } else if (stem < 1e24) {
            return stemDecimals(stem, 23);
        } else if (stem < 1e25) {
            return stemDecimals(stem, 24);
        } else if (stem < 1e26) {
            return stemDecimals(stem, 25);
        } else if (stem < 1e27) {
            return stemDecimals(stem, 26);
        } else if (stem < 1e28) {
            return stemDecimals(stem, 27);
        } else {
            return stemDecimals(stem, 28);
        }
    }
    
    function stemDecimals(uint256 stem, uint256 exponent) internal pure returns (string memory) {
        return string(abi.encodePacked(
            stem.div(10 ** exponent).toString(),
            '.',
            stem.div(10 ** exponent.sub(5)).mod(1e5).toString(),
            'e',
            exponent.toString()
        ));
    }

    function tokenName(address token) internal view returns (string memory) {
        return string(
            abi.encodePacked(
                '<text x="10" y="14.5" font-size="12" fill="White" text-anchor="start" font-family="futura">',
                getTokenName(token),
                '</text>'
            )
        );
    }

    function movingTokenAddress(address token) internal pure returns (string memory) {
        return string(
            abi.encodePacked(
                '<text x="127" y="343" font-size="10" fill="White" text-anchor="middle" font-family="futura">',
                '<tspan><animate attributeName="x" from="375" to="50" dur="10s" repeatCount="indefinite" />',
                LibStrings.toHexString(token),
                '</tspan></text>',
                '<text x="127" y="343" font-size="10" fill="White" text-anchor="middle" font-family="futura">',
                '<tspan><animate attributeName="x" from="50" to="-275" dur="10s" repeatCount="indefinite" />',
                LibStrings.toHexString(token),
                '</tspan></text>'
            )
        );
    }

    function intToStr(int256 x) internal pure returns (string memory) {
        if (x < 0) {
            return string(abi.encodePacked(
                '-',
                uint256(-x).toString()
            ));
        } else {
            return uint256(x).toString();
        }        
    }

    
    function getTokenName(address token) internal view returns (string memory tokenString) {
        // for unripe LP, return `urLP` given the current unripe name is inaccurate. 
        if (token == C.UNRIPE_LP) {
            tokenString = "urBEANLP";
        } else {
            tokenString = ERC20(token).symbol();
        }
    }

    function getNumStemsAndPlots(int96 grownStalkPerBDV) 
        internal 
        pure 
        returns (uint256 numStems, uint256 plots)
    {
        // 1 sprout on the image is equal to 0.02 stalk
        numStems = uint256(grownStalkPerBDV).div(STALK_GROWTH);
        plots = numStems.div(16).add(1);
        if (numStems.mod(16) > 0) plots = plots.add(1);
    }
}

File 10 of 28 : C.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import "./interfaces/IBean.sol";
import "./interfaces/ICurve.sol";
import "./interfaces/IFertilizer.sol";
import "./interfaces/IProxyAdmin.sol";
import "./libraries/Decimal.sol";

/**
 * @title C
 * @author Publius
 * @notice Contains constants used throughout Beanstalk.
 */
library C {
    using Decimal for Decimal.D256;
    using SafeMath for uint256;

    //////////////////// Globals ////////////////////

    uint256 internal constant PRECISION = 1e18;
    uint256 private constant CHAIN_ID = 1;
    bytes constant BYTES_ZERO = new bytes(0);

    /// @dev The block time for the chain in seconds.
    uint256 internal constant BLOCK_LENGTH_SECONDS = 12;

    //////////////////// Season ////////////////////

    /// @dev The length of a Season meaured in seconds.
    uint256 private constant CURRENT_SEASON_PERIOD = 3600; // 1 hour
    uint256 internal constant SOP_PRECISION = 1e24;

    //////////////////// Silo ////////////////////

    uint256 internal constant SEEDS_PER_BEAN = 2;
    uint256 internal constant STALK_PER_BEAN = 10000;
    uint256 private constant ROOTS_BASE = 1e12;

    //////////////////// Exploit Migration ////////////////////

    uint256 private constant UNRIPE_LP_PER_DOLLAR = 1884592; // 145_113_507_403_282 / 77_000_000
    uint256 private constant ADD_LP_RATIO = 866616;
    uint256 private constant INITIAL_HAIRCUT = 185564685220298701;

    //////////////////// Contracts ////////////////////

    address internal constant BEAN = 0xBEA0000029AD1c77D3d5D23Ba2D8893dB9d1Efab;
    address internal constant CURVE_BEAN_METAPOOL = 0xc9C32cd16Bf7eFB85Ff14e0c8603cc90F6F2eE49;

    address internal constant UNRIPE_BEAN = 0x1BEA0050E63e05FBb5D8BA2f10cf5800B6224449;
    address internal constant UNRIPE_LP = 0x1BEA3CcD22F4EBd3d37d731BA31Eeca95713716D;

    address private constant CURVE_3_POOL = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
    address private constant THREE_CRV = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;

    address private constant FERTILIZER = 0x402c84De2Ce49aF88f5e2eF3710ff89bFED36cB6;
    address private constant FERTILIZER_ADMIN = 0xfECB01359263C12Aa9eD838F878A596F0064aa6e;

    address private constant TRI_CRYPTO = 0xc4AD29ba4B3c580e6D59105FFf484999997675Ff;
    address private constant TRI_CRYPTO_POOL = 0xD51a44d3FaE010294C616388b506AcdA1bfAAE46;
    address private constant CURVE_ZAP = 0xA79828DF1850E8a3A3064576f380D90aECDD3359;

    address private constant UNRIPE_CURVE_BEAN_LUSD_POOL = 0xD652c40fBb3f06d6B58Cb9aa9CFF063eE63d465D;
    address private constant UNRIPE_CURVE_BEAN_METAPOOL = 0x3a70DfA7d2262988064A2D051dd47521E43c9BdD;

    address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
    address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
    address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    address internal constant WSTETH = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0;

    // Use external contract for block.basefee as to avoid upgrading existing contracts to solidity v8
    address private constant BASE_FEE_CONTRACT = 0x84292919cB64b590C0131550483707E43Ef223aC;

    //////////////////// Well ////////////////////

    uint256 internal constant WELL_MINIMUM_BEAN_BALANCE = 1000_000_000; // 1,000 Beans
    address internal constant BEAN_ETH_WELL = 0xBEA0e11282e2bB5893bEcE110cF199501e872bAd;
    address internal constant BEAN_WSTETH_WELL = 0xBeA0000113B0d182f4064C86B71c315389E4715D;
    // The index of the Bean and Weth token addresses in all BEAN/ETH Wells.
    uint256 internal constant BEAN_INDEX = 0;
    uint256 internal constant ETH_INDEX = 1;

    function getSeasonPeriod() internal pure returns (uint256) {
        return CURRENT_SEASON_PERIOD;
    }

    function getBlockLengthSeconds() internal pure returns (uint256) {
        return BLOCK_LENGTH_SECONDS;
    }

    function getChainId() internal pure returns (uint256) {
        return CHAIN_ID;
    }

    function getSeedsPerBean() internal pure returns (uint256) {
        return SEEDS_PER_BEAN;
    }

    function getStalkPerBean() internal pure returns (uint256) {
      return STALK_PER_BEAN;
    }

    function getRootsBase() internal pure returns (uint256) {
        return ROOTS_BASE;
    }

    /**
     * @dev The pre-exploit BEAN:3CRV Curve metapool address.
     */
    function unripeLPPool1() internal pure returns (address) {
        return UNRIPE_CURVE_BEAN_METAPOOL;
    }

    /**
     * @dev The pre-exploit BEAN:LUSD Curve plain pool address.
     */
    function unripeLPPool2() internal pure returns (address) {
        return UNRIPE_CURVE_BEAN_LUSD_POOL;
    }

    function unripeBean() internal pure returns (IERC20) {
        return IERC20(UNRIPE_BEAN);
    }

    function unripeLP() internal pure returns (IERC20) {
        return IERC20(UNRIPE_LP);
    }

    function bean() internal pure returns (IBean) {
        return IBean(BEAN);
    }

    function usdc() internal pure returns (IERC20) {
        return IERC20(USDC);
    }

    function curveMetapool() internal pure returns (ICurvePool) {
        return ICurvePool(CURVE_BEAN_METAPOOL);
    }

    function curve3Pool() internal pure returns (I3Curve) {
        return I3Curve(CURVE_3_POOL);
    }
    
    function curveZap() internal pure returns (ICurveZap) {
        return ICurveZap(CURVE_ZAP);
    }

    function curveZapAddress() internal pure returns (address) {
        return CURVE_ZAP;
    }

    function curve3PoolAddress() internal pure returns (address) {
        return CURVE_3_POOL;
    }

    function threeCrv() internal pure returns (IERC20) {
        return IERC20(THREE_CRV);
    }

    function fertilizer() internal pure returns (IFertilizer) {
        return IFertilizer(FERTILIZER);
    }

    function fertilizerAddress() internal pure returns (address) {
        return FERTILIZER;
    }

    function fertilizerAdmin() internal pure returns (IProxyAdmin) {
        return IProxyAdmin(FERTILIZER_ADMIN);
    }

    function triCryptoPoolAddress() internal pure returns (address) {
        return TRI_CRYPTO_POOL;
    }

    function triCrypto() internal pure returns (IERC20) {
        return IERC20(TRI_CRYPTO);
    }

    function unripeLPPerDollar() internal pure returns (uint256) {
        return UNRIPE_LP_PER_DOLLAR;
    }

    function dollarPerUnripeLP() internal pure returns (uint256) {
        return 1e12/UNRIPE_LP_PER_DOLLAR;
    }

    function exploitAddLPRatio() internal pure returns (uint256) {
        return ADD_LP_RATIO;
    }

    function precision() internal pure returns (uint256) {
        return PRECISION;
    }

    function initialRecap() internal pure returns (uint256) {
        return INITIAL_HAIRCUT;
    }

}

File 11 of 28 : IBean.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/**
 * @title IBean
 * @author Publius
 * @notice Bean Interface
 */
abstract contract IBean is IERC20 {
    function burn(uint256 amount) public virtual;
    function burnFrom(address account, uint256 amount) public virtual;
    function mint(address account, uint256 amount) public virtual;
    function symbol() public view virtual returns (string memory);
}

File 12 of 28 : ICurve.sol
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity =0.7.6;

interface ICurvePool {
    function A_precise() external view returns (uint256);
    function get_balances() external view returns (uint256[2] memory);
    function totalSupply() external view returns (uint256);
    function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external returns (uint256);
    function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount) external returns (uint256);
    function balances(int128 i) external view returns (uint256);
    function fee() external view returns (uint256);
    function coins(uint256 i) external view returns (address);
    function get_virtual_price() external view returns (uint256);
    function calc_token_amount(uint256[2] calldata amounts, bool deposit) external view returns (uint256);
    function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);
    function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256);
    function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256);
    function transfer(address recipient, uint256 amount) external returns (bool);
}

interface ICurveZap {
    function add_liquidity(address _pool, uint256[4] memory _deposit_amounts, uint256 _min_mint_amount) external returns (uint256);
    function calc_token_amount(address _pool, uint256[4] memory _amounts, bool _is_deposit) external returns (uint256);
}

interface ICurvePoolR {
    function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
    function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
    function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount, address receiver) external returns (uint256);
}

interface ICurvePool2R {
    function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount, address reciever) external returns (uint256);
    function remove_liquidity(uint256 _burn_amount, uint256[2] memory _min_amounts, address reciever) external returns (uint256[2] calldata);
    function remove_liquidity_imbalance(uint256[2] memory _amounts, uint256 _max_burn_amount, address reciever) external returns (uint256);
}

interface ICurvePool3R {
    function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount, address reciever) external returns (uint256);
    function remove_liquidity(uint256 _burn_amount, uint256[3] memory _min_amounts, address reciever) external returns (uint256[3] calldata);
    function remove_liquidity_imbalance(uint256[3] memory _amounts, uint256 _max_burn_amount, address reciever) external returns (uint256);
}

interface ICurvePool4R {
    function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount, address reciever) external returns (uint256);
    function remove_liquidity(uint256 _burn_amount, uint256[4] memory _min_amounts, address reciever) external returns (uint256[4] calldata);
    function remove_liquidity_imbalance(uint256[4] memory _amounts, uint256 _max_burn_amount, address reciever) external returns (uint256);
}

interface I3Curve {
    function get_virtual_price() external view returns (uint256);
}

interface ICurveFactory {
    function get_coins(address _pool) external view returns (address[4] calldata);
    function get_underlying_coins(address _pool) external view returns (address[8] calldata);
}

interface ICurveCryptoFactory {
    function get_coins(address _pool) external view returns (address[8] calldata);
}

interface ICurvePoolC {
    function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external returns (uint256);
}

interface ICurvePoolNoReturn {
    function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external;
    function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external;
    function remove_liquidity(uint256 _burn_amount, uint256[3] memory _min_amounts) external;
    function remove_liquidity_imbalance(uint256[3] memory _amounts, uint256 _max_burn_amount) external;
    function remove_liquidity_one_coin(uint256 _token_amount, uint256 i, uint256 min_amount) external;
}

interface ICurvePoolNoReturn128 {
    function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external;
    function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount) external;
}

File 13 of 28 : IDiamondCut.sol
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity =0.7.6;
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
/******************************************************************************/

interface IDiamondCut {
    enum FacetCutAction {Add, Replace, Remove}

    struct FacetCut {
        address facetAddress;
        FacetCutAction action;
        bytes4[] functionSelectors;
    }

    /// @notice Add/replace/remove any number of functions and optionally execute
    ///         a function with delegatecall
    /// @param _diamondCut Contains the facet addresses and function selectors
    /// @param _init The address of the contract or facet to execute _calldata
    /// @param _calldata A function call, including function selector and arguments
    ///                  _calldata is executed with delegatecall on _init
    function diamondCut(
        FacetCut[] calldata _diamondCut,
        address _init,
        bytes calldata _calldata
    ) external;

    event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
}

File 14 of 28 : IFertilizer.sol
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity =0.7.6;

interface IFertilizer {
    struct Balance {
        uint128 amount;
        uint128 lastBpf;
    }
    function beanstalkUpdate(
        address account,
        uint256[] memory ids,
        uint128 bpf
    ) external returns (uint256);
    function beanstalkMint(address account, uint256 id, uint128 amount, uint128 bpf) external;
    function balanceOfFertilized(address account, uint256[] memory ids) external view returns (uint256);
    function balanceOfUnfertilized(address account, uint256[] memory ids) external view returns (uint256);
    function lastBalanceOf(address account, uint256 id) external view returns (Balance memory);
    function lastBalanceOfBatch(address[] memory account, uint256[] memory id) external view returns (Balance[] memory);
    function setURI(string calldata newuri) external;
}

File 15 of 28 : IProxyAdmin.sol
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity =0.7.6;
interface IProxyAdmin {
    function upgrade(address proxy, address implementation) external;
}

File 16 of 28 : Decimal.sol
/*
 SPDX-License-Identifier: MIT
*/

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";

/**
 * @title Decimal
 * @author dYdX
 *
 * Library that defines a fixed-point number with 18 decimal places.
 */
library Decimal {
    using SafeMath for uint256;

    // ============ Constants ============

    uint256 constant BASE = 10**18;

    // ============ Structs ============


    struct D256 {
        uint256 value;
    }

    // ============ Static Functions ============

    function zero()
    internal
    pure
    returns (D256 memory)
    {
        return D256({ value: 0 });
    }

    function one()
    internal
    pure
    returns (D256 memory)
    {
        return D256({ value: BASE });
    }

    function from(
        uint256 a
    )
    internal
    pure
    returns (D256 memory)
    {
        return D256({ value: a.mul(BASE) });
    }

    function ratio(
        uint256 a,
        uint256 b
    )
    internal
    pure
    returns (D256 memory)
    {
        return D256({ value: getPartial(a, BASE, b) });
    }

    // ============ Self Functions ============

    function add(
        D256 memory self,
        uint256 b
    )
    internal
    pure
    returns (D256 memory)
    {
        return D256({ value: self.value.add(b.mul(BASE)) });
    }

    function sub(
        D256 memory self,
        uint256 b
    )
    internal
    pure
    returns (D256 memory)
    {
        return D256({ value: self.value.sub(b.mul(BASE)) });
    }

    function sub(
        D256 memory self,
        uint256 b,
        string memory reason
    )
    internal
    pure
    returns (D256 memory)
    {
        return D256({ value: self.value.sub(b.mul(BASE), reason) });
    }

    function mul(
        D256 memory self,
        uint256 b
    )
    internal
    pure
    returns (D256 memory)
    {
        return D256({ value: self.value.mul(b) });
    }

    function div(
        D256 memory self,
        uint256 b
    )
    internal
    pure
    returns (D256 memory)
    {
        return D256({ value: self.value.div(b) });
    }

    function pow(
        D256 memory self,
        uint256 b
    )
    internal
    pure
    returns (D256 memory)
    {
        if (b == 0) {
            return one();
        }

        D256 memory temp = D256({ value: self.value });
        for (uint256 i = 1; i < b; ++i) {
            temp = mul(temp, self);
        }

        return temp;
    }

    function add(
        D256 memory self,
        D256 memory b
    )
    internal
    pure
    returns (D256 memory)
    {
        return D256({ value: self.value.add(b.value) });
    }

    function sub(
        D256 memory self,
        D256 memory b
    )
    internal
    pure
    returns (D256 memory)
    {
        return D256({ value: self.value.sub(b.value) });
    }

    function sub(
        D256 memory self,
        D256 memory b,
        string memory reason
    )
    internal
    pure
    returns (D256 memory)
    {
        return D256({ value: self.value.sub(b.value, reason) });
    }

    function mul(
        D256 memory self,
        D256 memory b
    )
    internal
    pure
    returns (D256 memory)
    {
        return D256({ value: getPartial(self.value, b.value, BASE) });
    }

    function div(
        D256 memory self,
        D256 memory b
    )
    internal
    pure
    returns (D256 memory)
    {
        return D256({ value: getPartial(self.value, BASE, b.value) });
    }

    function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
        return self.value == b.value;
    }

    function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
        return compareTo(self, b) == 2;
    }

    function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
        return compareTo(self, b) == 0;
    }

    function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
        return compareTo(self, b) > 0;
    }

    function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
        return compareTo(self, b) < 2;
    }

    function isZero(D256 memory self) internal pure returns (bool) {
        return self.value == 0;
    }

    function asUint256(D256 memory self) internal pure returns (uint256) {
        return self.value.div(BASE);
    }

    // ============ Core Methods ============

    function getPartial(
        uint256 target,
        uint256 numerator,
        uint256 denominator
    )
    private
    pure
    returns (uint256)
    {
        return target.mul(numerator).div(denominator);
    }

    function compareTo(
        D256 memory a,
        D256 memory b
    )
    private
    pure
    returns (uint256)
    {
        if (a.value == b.value) {
            return 1;
        }
        return a.value > b.value ? 2 : 0;
    }
}

File 17 of 28 : LibAppStorage.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

// Import all of AppStorage to give importers of LibAppStorage access to {Account}, etc.
import "../beanstalk/AppStorage.sol";

/**
 * @title LibAppStorage 
 * @author Publius
 * @notice Allows libaries to access Beanstalk's state.
 */
library LibAppStorage {
    function diamondStorage() internal pure returns (AppStorage storage ds) {
        assembly {
            ds.slot := 0
        }
    }
}

File 18 of 28 : LibBytes.sol
/**
 * SPDX-License-Identifier: MIT
 **/
 
pragma solidity =0.7.6;

/* 
* @author: Malteasy
* @title: LibBytes
*/

library LibBytes {

    /*
    * @notice From Solidity Bytes Arrays Utils
    * @author Gonçalo Sá <[email protected]>
    */
    function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
        require(_start + 1 >= _start, "toUint8_overflow");
        require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
        uint8 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x1), _start))
        }

        return tempUint;
    }

    /*
    * @notice From Solidity Bytes Arrays Utils
    * @author Gonçalo Sá <[email protected]>
    */
    function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
        require(_start + 4 >= _start, "toUint32_overflow");
        require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
        uint32 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x4), _start))
        }

        return tempUint;
    }

    /*
    * @notice From Solidity Bytes Arrays Utils
    * @author Gonçalo Sá <[email protected]>
    */
    function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
        require(_start + 32 >= _start, "toUint256_overflow");
        require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
        uint256 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x20), _start))
        }

        return tempUint;
    }

    /**
    * @notice Loads a slice of a calldata bytes array into memory
    * @param b The calldata bytes array to load from
    * @param start The start of the slice
    * @param length The length of the slice
    */
    function sliceToMemory(bytes calldata b, uint256 start, uint256 length) internal pure returns (bytes memory) {
        bytes memory memBytes = new bytes(length);
        for(uint256 i = 0; i < length; ++i) {
            memBytes[i] = b[start + i];
        }
        return memBytes;
    }

    function packAddressAndStem(address _address, int96 stem) internal pure returns (uint256) {
        return uint256(_address) << 96 | uint96(stem);
    }

    function unpackAddressAndStem(uint256 data) internal pure returns(address, int96) {
        return (address(uint160(data >> 96)), int96(int256(data)));
    }


}

File 19 of 28 : LibBytes64.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;

/**
 * @author Brean
 * @dev Provides a set of functions to operate with Base64 strings.
 * @title Base64 is a 0.7.6 variation of Open Zeppelin's Base64.
 *
 */
library LibBytes64 {
    /**
     * @dev Base64 Encoding/Decoding Table
     */
    string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    /**
     * @dev Converts a `bytes` to its Bytes64 `string` representation.
     */
    function encode(bytes memory data) internal pure returns (string memory) {
        /**
         * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
         * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
         */
        if (data.length == 0) return "";

        // Loads the table into memory
        string memory table = _TABLE;

        // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
        // and split into 4 numbers of 6 bits.
        // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
        // - `data.length + 2`  -> Round up
        // - `/ 3`              -> Number of 3-bytes chunks
        // - `4 *`              -> 4 characters for each chunk
        string memory result = new string(4 * ((data.length + 2) / 3));

        assembly {
            // Prepare the lookup table (skip the first "length" byte)
            let tablePtr := add(table, 1)

            // Prepare result pointer, jump over length
            let resultPtr := add(result, 32)

            // Run over the input, 3 bytes at a time
            for {
                let dataPtr := data
                let endPtr := add(data, mload(data))
            } lt(dataPtr, endPtr) {

            } {
                // Advance 3 bytes
                dataPtr := add(dataPtr, 3)
                let input := mload(dataPtr)

                // To write each character, shift the 3 bytes (18 bits) chunk
                // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
                // and apply logical AND with 0x3F which is the number of
                // the previous character in the ASCII table prior to the Base64 Table
                // The result is then added to the table to get the character to write,
                // and finally write it in the result pointer but with a left shift
                // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits

                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance
            }

            // When data `bytes` is not exactly 3 bytes long
            // it is padded with `=` characters at the end
            switch mod(mload(data), 3)
            case 1 {
                mstore8(sub(resultPtr, 1), 0x3d)
                mstore8(sub(resultPtr, 2), 0x3d)
            }
            case 2 {
                mstore8(sub(resultPtr, 1), 0x3d)
            }
        }

        return result;
    }
}

File 20 of 28 : LibSafeMath128.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @author Publius
 * @title LibSafeMath128 is a uint128 variation of Open Zeppelin's Safe Math library.
**/
library LibSafeMath128 {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint128 a, uint128 b) internal pure returns (bool, uint128) {
        uint128 c = a + b;
        if (c < a) return (false, 0);
        return (true, c);
    }

    /**
     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint128 a, uint128 b) internal pure returns (bool, uint128) {
        if (b > a) return (false, 0);
        return (true, a - b);
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint128 a, uint128 b) internal pure returns (bool, uint128) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) return (true, 0);
        uint128 c = a * b;
        if (c / a != b) return (false, 0);
        return (true, c);
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint128 a, uint128 b) internal pure returns (bool, uint128) {
        if (b == 0) return (false, 0);
        return (true, a / b);
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint128 a, uint128 b) internal pure returns (bool, uint128) {
        if (b == 0) return (false, 0);
        return (true, a % b);
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint128 a, uint128 b) internal pure returns (uint128) {
        uint128 c = a + b;
        require(c >= a, "SafeMath: addition overflow");
        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint128 a, uint128 b) internal pure returns (uint128) {
        require(b <= a, "SafeMath: subtraction overflow");
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint128 a, uint128 b) internal pure returns (uint128) {
        if (a == 0) return 0;
        uint128 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");
        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint128 a, uint128 b) internal pure returns (uint128) {
        require(b > 0, "SafeMath: division by zero");
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint128 a, uint128 b) internal pure returns (uint128) {
        require(b > 0, "SafeMath: modulo by zero");
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {
        require(b <= a, errorMessage);
        return a - b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryDiv}.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {
        require(b > 0, errorMessage);
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {
        require(b > 0, errorMessage);
        return a % b;
    }
}

File 21 of 28 : LibSafeMath32.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @author Publius
 * @title LibSafeMath32 is a uint32 variation of Open Zeppelin's Safe Math library.
**/
library LibSafeMath32 {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint32 a, uint32 b) internal pure returns (bool, uint32) {
        uint32 c = a + b;
        if (c < a) return (false, 0);
        return (true, c);
    }

    /**
     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint32 a, uint32 b) internal pure returns (bool, uint32) {
        if (b > a) return (false, 0);
        return (true, a - b);
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint32 a, uint32 b) internal pure returns (bool, uint32) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) return (true, 0);
        uint32 c = a * b;
        if (c / a != b) return (false, 0);
        return (true, c);
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint32 a, uint32 b) internal pure returns (bool, uint32) {
        if (b == 0) return (false, 0);
        return (true, a / b);
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint32 a, uint32 b) internal pure returns (bool, uint32) {
        if (b == 0) return (false, 0);
        return (true, a % b);
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint32 a, uint32 b) internal pure returns (uint32) {
        uint32 c = a + b;
        require(c >= a, "SafeMath: addition overflow");
        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint32 a, uint32 b) internal pure returns (uint32) {
        require(b <= a, "SafeMath: subtraction overflow");
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint32 a, uint32 b) internal pure returns (uint32) {
        if (a == 0) return 0;
        uint32 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");
        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint32 a, uint32 b) internal pure returns (uint32) {
        require(b > 0, "SafeMath: division by zero");
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint32 a, uint32 b) internal pure returns (uint32) {
        require(b > 0, "SafeMath: modulo by zero");
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) {
        require(b <= a, errorMessage);
        return a - b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryDiv}.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) {
        require(b > 0, errorMessage);
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) {
        require(b > 0, errorMessage);
        return a % b;
    }
}

File 22 of 28 : LibSafeMathSigned128.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @title SignedSafeMath
 * @dev Signed math operations with safety checks that revert on error.
 */
library LibSafeMathSigned128 {
    int128 constant private _INT128_MIN = -2**127;

    /**
     * @dev Returns the multiplication of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(int128 a, int128 b) internal pure returns (int128) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        require(!(a == -1 && b == _INT128_MIN), "SignedSafeMath: multiplication overflow");

        int128 c = a * b;
        require(c / a == b, "SignedSafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two signed integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(int128 a, int128 b) internal pure returns (int128) {
        require(b != 0, "SignedSafeMath: division by zero");
        require(!(b == -1 && a == _INT128_MIN), "SignedSafeMath: division overflow");

        int128 c = a / b;

        return c;
    }

    /**
     * @dev Returns the subtraction of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(int128 a, int128 b) internal pure returns (int128) {
        int128 c = a - b;
        require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");

        return c;
    }

    /**
     * @dev Returns the addition of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(int128 a, int128 b) internal pure returns (int128) {
        int128 c = a + b;
        require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");

        return c;
    }
}

File 23 of 28 : LibSafeMathSigned96.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @title SignedSafeMath
 * @dev Signed math operations with safety checks that revert on error.
 */
library LibSafeMathSigned96 {
    int96 constant private _INT96_MIN = -2**95;

    /**
     * @dev Returns the multiplication of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(int96 a, int96 b) internal pure returns (int96) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        require(!(a == -1 && b == _INT96_MIN), "SignedSafeMath: multiplication overflow");

        int96 c = a * b;
        require(c / a == b, "SignedSafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two signed integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(int96 a, int96 b) internal pure returns (int96) {
        require(b != 0, "SignedSafeMath: division by zero");
        require(!(b == -1 && a == _INT96_MIN), "SignedSafeMath: division overflow");

        int96 c = a / b;

        return c;
    }

    /**
     * @dev Returns the subtraction of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(int96 a, int96 b) internal pure returns (int96) {
        int96 c = a - b;
        require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");

        return c;
    }

    /**
     * @dev Returns the addition of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(int96 a, int96 b) internal pure returns (int96) {
        int96 c = a + b;
        require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");

        return c;
    }
}

File 24 of 28 : LibStrings.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev String operations.
 */
library LibStrings {

    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        uint256 index = digits - 1;
        temp = value;
        while (temp != 0) {
            buffer[index--] = bytes1(uint8(48 + temp % 10));
            temp /= 10;
        }
        return string(buffer);
    }

     function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` representation.
     */
    function toString(int256 value) internal pure returns(string memory){
        if(value > 0){
            return toString(uint256(value));
        } else {
            return string(abi.encodePacked("-", toString(uint256(-value))));
        }
    }
}

File 25 of 28 : LibGerminate.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import {LibAppStorage, Storage, AppStorage, Account} from "../LibAppStorage.sol";
import {LibSafeMath128} from "../LibSafeMath128.sol";
import {LibSafeMath32} from "../LibSafeMath32.sol";
import {LibSafeMathSigned96} from "../LibSafeMathSigned96.sol";
import {LibTokenSilo} from "./LibTokenSilo.sol";
import {LibSilo} from "./LibSilo.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {C} from "../../C.sol";

/**
 * @title LibGerminate
 * @author Brean
 * @notice LibGerminate handles logic associated with germination.
 * @dev "germinating" values are values that are currently inactive.
 * germinating values stay germinating until the 1 + the remainder of the current season as passed,
 * in which case they become active.
 *
 * The following are germinating:
 * - newly issued stalk (from new deposits or mowing)
 * - roots from newly issued stalk
 * - new bdv introduced in the silo.
 */
library LibGerminate {
    using SafeMath for uint256;
    using SafeCast for uint256;
    using LibSafeMath32 for uint32;
    using LibSafeMath128 for uint128;
    using LibSafeMathSigned96 for int96;

    //////////////////////// EVENTS ////////////////////////

    /**
     * @notice emitted when the farmers germinating stalk changes.
     */
    event FarmerGerminatingStalkBalanceChanged(
        address indexed account,
        int256 deltaGerminatingStalk,
        Germinate germinationState
    );

    /**
     * @notice emitted when the total germinating amount/bdv changes.
     * @param germinationSeason the season the germination occured.
     * Does not always equal the current season.
     * @param token the token being updated.
     * @param deltaAmount the change in the total germinating amount.
     * @param deltaBdv the change in the total germinating bdv.
     */
    event TotalGerminatingBalanceChanged(
        uint256 germinationSeason,
        address indexed token,
        int256 deltaAmount,
        int256 deltaBdv
    );

    /**
     * @notice emitted when the total germinating stalk changes.
     * @param germinationSeason issuance season of germinating stalk
     * @param deltaGerminatingStalk the change in the total germinating stalk.
     * @dev the issuance season may differ from the season that this event was emitted in..
     */
    event TotalGerminatingStalkChanged(uint256 germinationSeason, int256 deltaGerminatingStalk);

    /**
     * @notice emitted at the sunrise function when the total stalk and roots are incremented.
     * @dev currently, stalk and roots can only increase at the end of `endTotalGermination`,
     * but is casted in the event to allow for future decreases.
     */
    event TotalStalkChangedFromGermination(int256 deltaStalk, int256 deltaRoots);

    struct GermStem {
        int96 germinatingStem;
        int96 stemTip;
    }
    /**
     * @notice Germinate determines what germination struct to use.
     * @dev "odd" and "even" refers to the value of the season counter.
     * "Odd" germinations are used when the season is odd, and vice versa.
     */
    enum Germinate {
        ODD,
        EVEN,
        NOT_GERMINATING
    }

    /**
     * @notice Ends the germination process of system-wide values.
     * @dev we calculate the unclaimed germinating roots of 2 seasons ago
     * as the roots of the stalk should be calculated based on the total stalk
     * when germination finishes, rather than when germination starts.
     */
    function endTotalGermination(uint32 season, address[] memory tokens) external {
        AppStorage storage s = LibAppStorage.diamondStorage();

        // germination can only occur after season 3.
        if (season < 2) return;
        uint32 germinationSeason = season.sub(2);

        // base roots are used if there are no roots in the silo.
        // root calculation is skipped if no deposits have been made
        // in the season.
        uint128 finishedGerminatingStalk = s.unclaimedGerminating[germinationSeason].stalk;
        uint128 rootsFromGerminatingStalk;
        if (s.s.roots == 0) {
            rootsFromGerminatingStalk = finishedGerminatingStalk.mul(uint128(C.getRootsBase()));
        } else if (s.unclaimedGerminating[germinationSeason].stalk > 0) {
            rootsFromGerminatingStalk = s.s.roots.mul(finishedGerminatingStalk).div(s.s.stalk).toUint128();
        }
        s.unclaimedGerminating[germinationSeason].roots = rootsFromGerminatingStalk;
        // increment total stalk and roots based on unclaimed values.
        s.s.stalk = s.s.stalk.add(finishedGerminatingStalk);
        s.s.roots = s.s.roots.add(rootsFromGerminatingStalk);

        // increment total deposited and amounts for each token.
        Storage.TotalGerminating storage totalGerm;
        if (getSeasonGerminationState() == Germinate.ODD) {
            totalGerm = s.oddGerminating;
        } else {
            totalGerm = s.evenGerminating;
        }
        for (uint i; i < tokens.length; ++i) {
            // if the token has no deposits, skip.
            if (totalGerm.deposited[tokens[i]].amount == 0) {
                continue;
            }

            LibTokenSilo.incrementTotalDeposited(
                tokens[i],
                totalGerm.deposited[tokens[i]].amount,
                totalGerm.deposited[tokens[i]].bdv
            );

            // emit events.
            emit TotalGerminatingBalanceChanged(
                germinationSeason,
                tokens[i],
                -int256(totalGerm.deposited[tokens[i]].amount),
                -int256(totalGerm.deposited[tokens[i]].bdv)
            );
            // clear deposited values.
            delete totalGerm.deposited[tokens[i]];
        }

        // emit change in total germinating stalk.
        // safecast not needed as finishedGerminatingStalk is initially a uint128.
        emit TotalGerminatingStalkChanged(germinationSeason, -int256(finishedGerminatingStalk));
        emit TotalStalkChangedFromGermination(int256(finishedGerminatingStalk), int256(rootsFromGerminatingStalk));
    }

    /**
     * @notice contains logic for ending germination for stalk and roots.
     * @param account address of the account to end germination for.
     * @param lastMowedSeason the last season the account mowed.
     *
     * @dev `first` refers to the set of germinating stalk
     * and roots created in the season closest to the current season.
     * i.e if a user deposited in season 10 and 11, the `first` stalk
     * would be season 11.
     *
     * the germination process:
     * - increments the assoicated values (bdv, stalk, roots)
     * - clears the germination struct for the account.
     * 
     * @return firstGerminatingRoots the roots from the first germinating stalk.
     * used in {handleRainAndSops} to properly set the rain roots of a user,
     * if the user had deposited in the season prior to a rain.
     */
    function endAccountGermination(
        address account,
        uint32 lastMowedSeason,
        uint32 currentSeason
    ) internal returns (uint128 firstGerminatingRoots) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        bool lastUpdateOdd = isSeasonOdd(lastMowedSeason);
        (uint128 firstStalk, uint128 secondStalk) = getGerminatingStalk(account, lastUpdateOdd);
        uint128 totalRootsFromGermination;
        uint128 germinatingStalk;

        // check to end germination for first stalk.
        // if last mowed season is greater or equal than (currentSeason - 1),
        // then the first stalk is still germinating.
        if (firstStalk > 0 && lastMowedSeason < currentSeason.sub(1)) {
            (uint128 roots, Germinate germState) = claimGerminatingRoots(
                account,
                lastMowedSeason,
                firstStalk,
                lastUpdateOdd
            );
            germinatingStalk = firstStalk;
            totalRootsFromGermination = roots;
            firstGerminatingRoots = roots;
            emit FarmerGerminatingStalkBalanceChanged(
                account,
                -int256(germinatingStalk),
                germState
            );
        }

        // check to end germination for second stalk.
        if (secondStalk > 0) {
            (uint128 roots, Germinate germState) = claimGerminatingRoots(
                account,
                lastMowedSeason.sub(1),
                secondStalk,
                !lastUpdateOdd
            );
            germinatingStalk = germinatingStalk.add(secondStalk);
            totalRootsFromGermination = totalRootsFromGermination.add(roots);
            emit FarmerGerminatingStalkBalanceChanged(account, -int256(germinatingStalk), germState);
        }

        // increment users stalk and roots.
        if (germinatingStalk > 0) {
            s.a[account].s.stalk = s.a[account].s.stalk.add(germinatingStalk);
            s.a[account].roots = s.a[account].roots.add(totalRootsFromGermination);

            // emit event. Active stalk is incremented, germinating stalk is decremented.
            emit LibSilo.StalkBalanceChanged(
                account,
                int256(germinatingStalk),
                int256(totalRootsFromGermination)
            );
        }
    }

    /**
     * @notice Claims the germinating roots of an account,
     * as well as clears the germinating stalk and roots.
     *
     * @param account address of the account to end germination for.
     * @param season the season to calculate the germinating roots for.
     * @param stalk the stalk to calculate the germinating roots for.
     * @param clearOdd whether to clear the odd or even germinating stalk.
     */
    function claimGerminatingRoots(
        address account,
        uint32 season,
        uint128 stalk,
        bool clearOdd
    ) private returns (uint128 roots, Germinate germState) {
        AppStorage storage s = LibAppStorage.diamondStorage();

        roots = calculateGerminatingRoots(season, stalk);

        if (clearOdd) {
            delete s.a[account].farmerGerminating.odd;
            germState = Germinate.ODD;
        } else {
            delete s.a[account].farmerGerminating.even;
            germState = Germinate.EVEN;
        }

        // deduct from unclaimed values.
        s.unclaimedGerminating[season].stalk = s.unclaimedGerminating[season].stalk.sub(stalk);
        s.unclaimedGerminating[season].roots = s.unclaimedGerminating[season].roots.sub(roots);
    }

    /**
     * @notice calculates the germinating roots for a given stalk and season.
     * @param season the season to use when calculating the germinating roots.
     * @param stalk the stalk to calculate the germinating roots for.
     */
    function calculateGerminatingRoots(
        uint32 season,
        uint128 stalk
    ) private view returns (uint128 roots) {
        AppStorage storage s = LibAppStorage.diamondStorage();

        // if the stalk is equal to the remaining unclaimed germinating stalk,
        // then return the remaining unclaimed germinating roots.
        if (stalk == s.unclaimedGerminating[season].stalk) {
            roots = s.unclaimedGerminating[season].roots;
        } else {
            // calculate the roots. casted up to uint256 to prevent overflow,
            // and safecasted down.
            roots = uint256(stalk).mul(s.unclaimedGerminating[season].roots).div(
                s.unclaimedGerminating[season].stalk
            ).toUint128();
        }
    }

    /**
     * @notice returns the germinatingStalk of the account,
     * ordered based on the parity of lastUpdate.
     * @dev if lastUpdate is odd, then `firstStalk` is the odd stalk.
     */
    function getGerminatingStalk(
        address account,
        bool lastUpdateOdd
    ) internal view returns (uint128 firstStalk, uint128 secondStalk) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        if (lastUpdateOdd) {
            firstStalk = s.a[account].farmerGerminating.odd;
            secondStalk = s.a[account].farmerGerminating.even;
        } else {
            firstStalk = s.a[account].farmerGerminating.even;
            secondStalk = s.a[account].farmerGerminating.odd;
        }
    }

    /**
     * @notice returns the germinating stalk and roots that will finish germinating
     * upon an interaction with the silo.
     */
    function getFinishedGerminatingStalkAndRoots(
        address account,
        uint32 lastMowedSeason,
        uint32 currentSeason
    ) internal view returns (uint256 germinatingStalk, uint256 germinatingRoots) {
        // if user has mowed already,
        // then there are no germinating stalk and roots to finish.
        if (lastMowedSeason == currentSeason) {
            return (0, 0);
        }

        (uint128 firstStalk, uint128 secondStalk) = getGerminatingStalk(
            account,
            isSeasonOdd(lastMowedSeason)
        );

        // check to end germination for first stalk.
        // if last mowed season is the greater or equal than (currentSeason - 1),
        // then the first stalk is still germinating.
        if (firstStalk > 0 && lastMowedSeason < currentSeason.sub(1)) {
            germinatingStalk = firstStalk;
            germinatingRoots = calculateGerminatingRoots(lastMowedSeason, firstStalk);
        }

        // check to end germination for second stalk.
        if (secondStalk > 0) {
            germinatingStalk = germinatingStalk.add(secondStalk);
            germinatingRoots = germinatingRoots.add(
                calculateGerminatingRoots(lastMowedSeason.sub(1), secondStalk)
            );
        }
    }

    /**
     * @notice returns the stalk currently germinating for an account.
     * Does not include germinating stalk that will finish germinating
     * upon an interaction with the silo.
     */
    function getCurrentGerminatingStalk(
        address account,
        uint32 lastMowedSeason
    ) internal view returns (uint256 germinatingStalk) {
        AppStorage storage s = LibAppStorage.diamondStorage();

        // if the last mowed season is less than the current season - 1,
        // then there are no germinating stalk and roots (as all germinating assets have finished).
        if (lastMowedSeason < s.season.current.sub(1)) {
            return 0;
        } else {
            (uint128 firstStalk, uint128 secondStalk) = getGerminatingStalk(
                account,
                isSeasonOdd(lastMowedSeason)
            );
            germinatingStalk = firstStalk.add(secondStalk);
        }
    }

    /**
     * @notice returns the unclaimed germinating stalk and roots.
     */
    function getUnclaimedGerminatingStalkAndRoots(
        uint32 season
    ) internal view returns (Storage.Sr memory unclaimed) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        unclaimed = s.unclaimedGerminating[season];
    }

    /**
     * @notice returns the total germinating bdv and amount for a token.
     */
    function getTotalGerminatingForToken(
        address token
    ) internal view returns (uint256 bdv, uint256 amount) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        return (
            s.oddGerminating.deposited[token].bdv.add(s.evenGerminating.deposited[token].bdv),
            s.oddGerminating.deposited[token].amount.add(s.evenGerminating.deposited[token].amount)
        );
    }

    /**
     * @notice determines whether a deposit (token + stem) should be germinating or not.
     * If germinating, determines whether the deposit should be set to even or odd.
     *
     * @dev `getGerminationState` should be used if the stemTip and germinatingStem
     * have not been calculated yet. Otherwise, use `_getGerminationState` for gas effiecnecy.
     */
    function getGerminationState(
        address token,
        int96 stem
    ) internal view returns (Germinate, int96) {
        GermStem memory germStem = getGerminatingStem(token);
        return (_getGerminationState(stem, germStem), germStem.stemTip);
    }

    /**
     * @notice returns the `germinating` stem of a token.
     * @dev the 'germinating' stem is the stem where deposits that have a stem
     * equal or higher than this value are germinating.
     */
    function getGerminatingStem(address token) internal view returns (GermStem memory germStem) {
        germStem.stemTip = LibTokenSilo.stemTipForToken(token);
        germStem.germinatingStem = _getGerminatingStem(token, germStem.stemTip);
    }

    /**
     * @notice returns the `germinating` stem of a token.
     * @dev the 'germinating' stem is the stem where deposits that have a stem
     * equal or higher than this value are germinating.
     */
    function _getGerminatingStem(address token, int96 stemTip) internal view returns (int96 stem) {
        return __getGerminatingStem(stemTip, getPrevStalkEarnedPerSeason(token));
    }

    /**
     * @notice Gas efficent version of `_getGerminatingStem`.
     *
     * @dev use when the stemTip and germinatingStem have already been calculated.
     * Assumes the same token is used.
     * prevStalkEarnedPerSeason is the stalkEarnedPerSeason of the previous season.
     * since `lastStemTip` + `prevStalkEarnedPerSeason` is the current stemTip, 
     * safeMath is not needed.
     */
    function __getGerminatingStem(
        int96 stemTip,
        int96 prevStalkEarnedPerSeason
    ) internal pure returns (int96 stem) {
        return stemTip - prevStalkEarnedPerSeason;
    }

    /**
     * @notice returns the stalkEarnedPerSeason of a token of the previous season.
     * @dev if the milestone season is not the current season, then the stalkEarnedPerSeason
     * hasn't changed from the previous season. Otherwise, we calculate the prevStalkEarnedPerSeason.
     */
    function getPrevStalkEarnedPerSeason(
        address token
    ) private view returns (uint32 prevStalkEarnedPerSeason) {
        AppStorage storage s = LibAppStorage.diamondStorage();

        if (s.ss[token].milestoneSeason < s.season.current) {
            prevStalkEarnedPerSeason = s.ss[token].stalkEarnedPerSeason;
        } else {
            int24 deltaStalkEarnedPerSeason = s.ss[token].deltaStalkEarnedPerSeason;
            if (deltaStalkEarnedPerSeason >= 0) {
                prevStalkEarnedPerSeason =
                    s.ss[token].stalkEarnedPerSeason -
                    uint32(deltaStalkEarnedPerSeason);
            } else {
                prevStalkEarnedPerSeason =
                    s.ss[token].stalkEarnedPerSeason +
                    uint32(-deltaStalkEarnedPerSeason);
            }
        }
    }

    /**
     * @notice internal function for germination stem.
     * @dev a deposit is germinating if the stem is the stemTip or the germinationStem.
     * the 'germinationStem` is the stem of the token of the previous season.
     *
     * The function must check whether the stem is equal to the germinationStem,
     * to determine which germination state it is in.
     */
    function _getGerminationState(
        int96 stem,
        GermStem memory germData
    ) internal view returns (Germinate) {
        if (stem < germData.germinatingStem) {
            // if the stem of the deposit is lower than the germination stem,
            // then the deposit is not germinating.
            return Germinate.NOT_GERMINATING;
        } else {
            // return the gemination state based on whether the stem
            // is equal to the stemTip.
            // if the stem is equal to the stem tip, it is in the initial stages of germination.
            // if the stem is not equal to the stemTip, its in the germination process.
            if (stem == germData.stemTip) {
                return isCurrentSeasonOdd() ? Germinate.ODD : Germinate.EVEN;
            } else {
                return isCurrentSeasonOdd() ? Germinate.EVEN : Germinate.ODD;
            }
        }
    }

    /**
     * @notice returns the germination state for the current season.
     * @dev used in new deposits, as all new deposits are germinating.
     */
    function getSeasonGerminationState() internal view returns (Germinate) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        return getGerminationStateForSeason(s.season.current);
    }

    /**
     * @notice returns the germination state for a given season.
     */
    function getGerminationStateForSeason(uint32 season) internal pure returns (Germinate) {
        return isSeasonOdd(season) ? Germinate.ODD : Germinate.EVEN;
    }

    /**
     * @notice returns whether the current season is odd. Used for Germination.
     * @dev even % 2 = 0 (false), odd % 2 = 1 (true)
     */
    function isCurrentSeasonOdd() internal view returns (bool) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        return isSeasonOdd(s.season.current);
    }

    /**
     * @notice returns whether `season` is odd.
     */
    function isSeasonOdd(uint32 season) internal pure returns (bool) {
        return season.mod(2) == 0 ? false : true;
    }

}

File 26 of 28 : LibSilo.sol
/**
 * SPDX-License-Identifier: MIT
 **/

pragma solidity =0.7.6;
pragma abicoder v2;

import "../LibAppStorage.sol";
import {C} from "../../C.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol";
import {LibBytes} from "../LibBytes.sol";
import {LibTokenSilo} from "./LibTokenSilo.sol";
import {LibSafeMath128} from "../LibSafeMath128.sol";
import {LibSafeMath32} from "../LibSafeMath32.sol";
import {LibSafeMathSigned96} from "../LibSafeMathSigned96.sol";
import {LibGerminate} from "./LibGerminate.sol";
import {LibWhitelistedTokens} from "./LibWhitelistedTokens.sol";

/**
 * @title LibSilo
 * @author Publius
 * @notice Contains functions for minting, burning, and transferring of
 * Stalk and Roots within the Silo.
 *
 * @dev Here, we refer to "minting" as the combination of
 * increasing the total balance of Stalk/Roots, as well as allocating
 * them to a particular account. However, in other places throughout Beanstalk
 * (like during the Sunrise), Beanstalk's total balance of Stalk increases
 * without allocating to a particular account. One example is {Sun-rewardToSilo}
 * which increases `s.s.stalk` but does not allocate it to any account. The
 * allocation occurs during `{SiloFacet-plant}`. Does this change how we should
 * call "minting"?
 *
 * In the ERC20 context, "minting" increases the supply of a token and allocates
 * the new tokens to an account in one action. I've adjusted the comments below
 * to use "mint" in the same sense.
 */
library LibSilo {
    using SafeMath for uint256;
    using LibSafeMath128 for uint128;
    using LibSafeMathSigned96 for int96;
    using LibSafeMath32 for uint32;
    using SafeCast for uint256;

    //////////////////////// ENUM ////////////////////////
    
    /**
     * @dev when a user removes multiple deposits, the
     * {TransferBatch} event is emitted. However, in the 
     * case of an enroot, the event is omitted (as the 
     * depositID does not change). This enum is
     * used to determine if the event should be emitted.
     */
    enum ERC1155Event {
        EMIT_BATCH_EVENT,
        NO_EMIT_BATCH_EVENT
    }
    

    uint128 internal constant PRECISION = 1e6;
    //////////////////////// EVENTS ////////////////////////

    /**
     * @notice Emitted when `account` gains or loses Stalk.
     * @param account The account that gained or lost Stalk.
     * @param delta The change in Stalk.
     * @param deltaRoots The change in Roots.
     *
     * @dev Should be emitted anytime a Deposit is added, removed or transferred
     * AND anytime an account Mows Grown Stalk.
     *
     * BIP-24 included a one-time re-emission of {StalkBalanceChanged} for
     * accounts that had executed a Deposit transfer between the Replant and
     * BIP-24 execution. For more, see:
     *
     * [BIP-24](https://bean.money/bip-24)
     * [Event-Emission](https://github.com/BeanstalkFarms/BIP-24-Event-Emission)
     */
    event StalkBalanceChanged(address indexed account, int256 delta, int256 deltaRoots);

    /**
     * @notice Emitted when a deposit is removed from the silo.
     *
     * @param account The account assoicated with the removed deposit.
     * @param token The token address of the removed deposit.
     * @param stem The stem of the removed deposit.
     * @param amount The amount of "token" removed from an deposit.
     * @param bdv The instanteous bdv removed from the deposit.
     */
    event RemoveDeposit(
        address indexed account,
        address indexed token,
        int96 stem,
        uint256 amount,
        uint256 bdv
    );

    /**
     * @notice Emitted when multiple deposits are removed from the silo.
     *
     * @param account The account assoicated with the removed deposit.
     * @param token The token address of the removed deposit.
     * @param stems A list of stems of the removed deposits.
     * @param amounts A list of amounts removed from the deposits.
     * @param amount the total summation of the amount removed.
     * @param bdvs A list of bdvs removed from the deposits.
     */
    event RemoveDeposits(
        address indexed account,
        address indexed token,
        int96[] stems,
        uint256[] amounts,
        uint256 amount,
        uint256[] bdvs
    );

    /**
     * AssetsRemoved contains the assets removed 
     * during a withdraw or convert. 
     * 
     * @dev seperated into 3 catagories:
     * active: non-germinating assets.
     * odd: odd germinating assets.
     * even: even germinating assets.
     * grownStalk from germinating depoists are seperated 
     * as that stalk is not germinating.
     */
    struct AssetsRemoved {
        Removed active;
        Removed odd; 
        Removed even;
        uint256 grownStalkFromGermDeposits;
    }

    struct Removed {
        uint256 tokens;
        uint256 stalk;
        uint256 bdv;
    }

    /**
     * @notice Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    //////////////////////// MINT ////////////////////////

   
    /**
     * @dev Mints Stalk and Roots to `account`.
     *
     * `roots` are an underlying accounting variable that is used to track
     * how many earned beans a user has.
     *
     * When a farmer's state is updated, the ratio should hold:
     *
     *  Total Roots     User Roots
     * ------------- = ------------
     *  Total Stalk     User Stalk
     *
     * @param account the address to mint Stalk and Roots to
     * @param stalk the amount of stalk to mint
     *
     * @dev Stalk that is not germinating are `active`, meaning that they 
     * are eligible for bean mints. To mint germinating stalk, use 
     * `mintGerminatingStalk`.
     */
    function mintActiveStalk(address account, uint256 stalk) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 roots;
        if (s.s.roots == 0) {
            roots = uint256(stalk.mul(C.getRootsBase()));
        } else {
            // germinating assets should be considered
            // when calculating roots
            roots = s.s.roots.mul(stalk).div(s.s.stalk);
        }

        // increment user and total stalk;
        s.s.stalk = s.s.stalk.add(stalk);
        s.a[account].s.stalk = s.a[account].s.stalk.add(stalk);

        // increment user and total roots
        s.s.roots = s.s.roots.add(roots);
        s.a[account].roots = s.a[account].roots.add(roots);

        emit StalkBalanceChanged(account, int256(stalk), int256(roots));
    }

    /**
     * @notice mintGerminatingStalk contains logic for minting stalk that is germinating.
     * @dev `germinating stalk` are newly issued stalk that are not eligible for bean mints,
     * until 2 `gm` calls have passed, at which point they are considered `grown stalk`.
     *
     * Since germinating stalk are not elgible for bean mints, when calculating the roots of these
     * stalk, it should use the stalk and roots of the system once the stalk is fully germinated,
     * rather than at the time of minting.
     */
    function mintGerminatingStalk(
        address account,
        uint128 stalk,
        LibGerminate.Germinate germ
    ) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();

        if (germ == LibGerminate.Germinate.ODD) {
            s.a[account].farmerGerminating.odd = s.a[account].farmerGerminating.odd.add(stalk);
        } else {
            s.a[account].farmerGerminating.even = s.a[account].farmerGerminating.even.add(stalk);
        }

        // germinating stalk are either newly germinating, or partially germinated.
        // Thus they can only be incremented in the latest or previous season.
        uint32 germinationSeason = s.season.current;
        if (LibGerminate.getSeasonGerminationState() == germ) {
            s.unclaimedGerminating[germinationSeason].stalk =
                s.unclaimedGerminating[germinationSeason].stalk.add(stalk);
        } else {
            germinationSeason = germinationSeason.sub(1);
            s.unclaimedGerminating[germinationSeason].stalk = 
                s.unclaimedGerminating[germinationSeason].stalk
                .add(stalk);
        }

        // emit events.
        emit LibGerminate.FarmerGerminatingStalkBalanceChanged(account, stalk, germ);
        emit LibGerminate.TotalGerminatingStalkChanged(germinationSeason, stalk);
    }

    //////////////////////// BURN ////////////////////////

    /**
     * @notice Burns stalk and roots from an account.
     */
    function burnActiveStalk(address account, uint256 stalk) internal returns (uint256 roots) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        if (stalk == 0) return 0;

        // Calculate the amount of Roots for the given amount of Stalk.
        roots = s.s.roots.mul(stalk).div(s.s.stalk);
        if (roots > s.a[account].roots) roots = s.a[account].roots;

        // Decrease supply of Stalk; Remove Stalk from the balance of `account`
        s.s.stalk = s.s.stalk.sub(stalk);
        s.a[account].s.stalk = s.a[account].s.stalk.sub(stalk);

        // Decrease supply of Roots; Remove Roots from the balance of `account`
        s.s.roots = s.s.roots.sub(roots);
        s.a[account].roots = s.a[account].roots.sub(roots);

        // If it is Raining and the account now has less roots than the
        // account's current rain roots, set the account's rain roots
        // to the account's current roots and subtract the difference
        // from Beanstalk's total rain roots.
        if (s.a[account].sop.roots > s.a[account].roots) {
            uint256 deltaRoots = s.a[account].sop.roots.sub(s.a[account].roots);
            s.a[account].sop.roots = s.a[account].roots;
            s.r.roots = s.r.roots.sub(deltaRoots);
        }

        // emit event.
        emit StalkBalanceChanged(account, -int256(stalk), -int256(roots));
    }

    /**
     * @notice Burns germinating stalk.
     * @dev Germinating stalk does not have any roots assoicated with it.
     */
    function burnGerminatingStalk(
        address account,
        uint128 stalk,
        LibGerminate.Germinate germ
    ) external {
        AppStorage storage s = LibAppStorage.diamondStorage();

        if (germ == LibGerminate.Germinate.ODD) {
            s.a[account].farmerGerminating.odd = s.a[account].farmerGerminating.odd.sub(stalk);
        } else {
            s.a[account].farmerGerminating.even = s.a[account].farmerGerminating.even.sub(stalk);
        }

        // germinating stalk are either newly germinating, or partially germinated.
        // Thus they can only be decremented in the latest or previous season.
        uint32 germinationSeason = s.season.current;
        if (LibGerminate.getSeasonGerminationState() == germ) {
            s.unclaimedGerminating[germinationSeason].stalk = 
                s.unclaimedGerminating[germinationSeason].stalk.sub(stalk);
        } else {
            germinationSeason = germinationSeason.sub(1);
            s.unclaimedGerminating[germinationSeason].stalk = 
                s.unclaimedGerminating[germinationSeason].stalk
                .sub(stalk);
        }

        // emit events.
        emit LibGerminate.FarmerGerminatingStalkBalanceChanged(account, -int256(stalk), germ);
        emit LibGerminate.TotalGerminatingStalkChanged(germinationSeason, -int256(stalk));
    }

    //////////////////////// TRANSFER ////////////////////////

    /**
     * @notice Decrements the Stalk and Roots of `sender` and increments the Stalk
     * and Roots of `recipient` by the same amount.
     *
     */
    function transferStalk(address sender, address recipient, uint256 stalk) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 roots;
        roots = stalk == s.a[sender].s.stalk
            ? s.a[sender].roots
            : s.s.roots.sub(1).mul(stalk).div(s.s.stalk).add(1);

        // Subtract Stalk and Roots from the 'sender' balance.
        s.a[sender].s.stalk = s.a[sender].s.stalk.sub(stalk);
        s.a[sender].roots = s.a[sender].roots.sub(roots);
        emit StalkBalanceChanged(sender, -int256(stalk), -int256(roots));

        // Rain roots cannot be transferred, burn them
        if (s.a[sender].sop.roots > s.a[sender].roots) {
            uint256 deltaRoots = s.a[sender].sop.roots.sub(s.a[sender].roots);
            s.a[sender].sop.roots = s.a[sender].roots;
            s.r.roots = s.r.roots.sub(deltaRoots);
        }

        // Add Stalk and Roots to the 'recipient' balance.
        s.a[recipient].s.stalk = s.a[recipient].s.stalk.add(stalk);
        s.a[recipient].roots = s.a[recipient].roots.add(roots);
        emit StalkBalanceChanged(recipient, int256(stalk), int256(roots));
    }

    /**
     * @notice germinating counterpart of `transferStalk`.
     * @dev assumes stalk is germinating.
     */
    function transferGerminatingStalk(
        address sender,
        address recipient,
        uint256 stalk,
        LibGerminate.Germinate germState
    ) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
         // Subtract Germinating Stalk from the 'sender' balance, 
         // and Add to the 'recipient' balance.
        if (germState == LibGerminate.Germinate.ODD) {
            s.a[sender].farmerGerminating.odd = s.a[sender].farmerGerminating.odd.sub(stalk.toUint128());
            s.a[recipient].farmerGerminating.odd = s.a[recipient].farmerGerminating.odd.add(stalk.toUint128());
        } else {
            s.a[sender].farmerGerminating.even = s.a[sender].farmerGerminating.even.sub(stalk.toUint128());
            s.a[recipient].farmerGerminating.even = s.a[recipient].farmerGerminating.even.add(stalk.toUint128());
        }

        // emit events.
        emit LibGerminate.FarmerGerminatingStalkBalanceChanged(sender, -int256(stalk), germState);
        emit LibGerminate.FarmerGerminatingStalkBalanceChanged(recipient, int256(stalk), germState);
    }

    /**
     * @notice transfers both stalk and Germinating Stalk.
     * @dev used in {TokenSilo._transferDeposits}
     */
    function transferStalkAndGerminatingStalk(
        address sender,
        address recipient,
        address token,
        AssetsRemoved memory ar
    ) external {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 stalkPerBDV = s.ss[token].stalkIssuedPerBdv;

        if (ar.odd.bdv > 0) {
            uint256 initialStalk = ar.odd.bdv.mul(stalkPerBDV);
            
            if (token == C.BEAN) {
                // check whether the Germinating Stalk transferred exceeds the farmers
                // Germinating Stalk. If so, the difference is considered from Earned 
                // Beans. Deduct the odd BDV and increment the activeBDV by the difference.
                (uint256 senderGerminatingStalk, uint256 earnedBeansStalk) = checkForEarnedBeans(
                    sender,
                    initialStalk,
                    LibGerminate.Germinate.ODD
                );
                if (earnedBeansStalk > 0) {
                    // increment the active stalk by the earned beans active stalk.
                    // decrement the germinatingStalk stalk by the earned beans active stalk.
                    ar.active.stalk = ar.active.stalk.add(earnedBeansStalk);
                    initialStalk = senderGerminatingStalk;
                }
            }
            // the inital Stalk issued for a Deposit is the 
            // only Stalk that can Germinate (i.e, Grown Stalk does not Germinate).
            transferGerminatingStalk(
                sender,
                recipient,
                initialStalk,
                LibGerminate.Germinate.ODD
            );
        }

        if (ar.even.bdv > 0) {
            uint256 initialStalk = ar.even.bdv.mul(stalkPerBDV);
           
            if (token == C.BEAN) {
                 // check whether the Germinating Stalk transferred exceeds the farmers
                // Germinating Stalk. If so, the difference is considered from Earned 
                // Beans. Deduct the even BDV and increment the active BDV by the difference.
                (uint256 senderGerminatingStalk, uint256 earnedBeansStalk) = checkForEarnedBeans(
                    sender,
                    initialStalk,
                    LibGerminate.Germinate.EVEN
                );
                if (earnedBeansStalk > 0) {
                    // increment the active stalk by the earned beans active stalk.
                    // decrement the germinatingStalk stalk by the earned beans active stalk.
                    ar.active.stalk = ar.active.stalk.add(earnedBeansStalk);
                    initialStalk = senderGerminatingStalk;
                }
            }
            // the inital Stalk issued for a Deposit is the 
            // only Stalk that can Germinate (i.e, Grown Stalk does not Germinate).
            transferGerminatingStalk(
                sender,
                recipient,
                initialStalk,
                LibGerminate.Germinate.EVEN
            );
        }

        // a Germinating Deposit may have Grown Stalk (which is not Germinating),
        // but the base Stalk is still Germinating.
        ar.active.stalk = ar.active.stalk // Grown Stalk from non-Germinating Deposits, and base stalk from Earned Bean Deposits.
            .add(ar.active.bdv.mul(stalkPerBDV)) // base stalk from non-germinating deposits.
            .add(ar.even.stalk) // grown stalk from Even Germinating Deposits.
            .add(ar.odd.stalk); // grown stalk from Odd Germinating Deposits.
        if (ar.active.stalk > 0) {
            transferStalk(sender, recipient, ar.active.stalk);
        }
    }

    /**
     * @dev Claims the Grown Stalk for `account` and applies it to their Stalk
     * balance. Also handles Season of Plenty related rain.
     *
     * This is why `_mow()` must be called before any actions that change Seeds,
     * including:
     *  - {SiloFacet-deposit}
     *  - {SiloFacet-withdrawDeposit}
     *  - {SiloFacet-withdrawDeposits}
     *  - {_plant}
     *  - {SiloFacet-transferDeposit(s)}
     */
    function _mow(address account, address token) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        
        // if the user has not migrated from siloV2, revert.
        (bool needsMigration, uint32 lastUpdate) = migrationNeeded(account);
        require(!needsMigration, "Silo: Migration needed");

        // if the user hasn't updated prior to the seedGauge/siloV3.1 update,
        // perform a one time `lastStem` scale.
        if (
            (lastUpdate < s.season.stemScaleSeason && lastUpdate > 0) || 
            (lastUpdate == s.season.stemScaleSeason && checkStemEdgeCase(account))
        ) {
            migrateStems(account);
        }

        uint32 currentSeason = s.season.current;
        
        // End account germination.
        uint128 firstGerminatingRoots;
        if (lastUpdate < currentSeason) {
            firstGerminatingRoots = LibGerminate.endAccountGermination(account, lastUpdate, currentSeason);
        }

        // sop data only needs to be updated once per season,
        // if it started raining and it's still raining, or there was a sop
        if (s.season.rainStart > s.season.stemStartSeason) {
            if ((lastUpdate <= s.season.rainStart || s.a[account].lastRain > 0) && lastUpdate <= currentSeason) {
                // Increments `plenty` for `account` if a Flood has occured.
                // Saves Rain Roots for `account` if it is Raining.
                handleRainAndSops(account, lastUpdate, firstGerminatingRoots);
            }
        }
        
        // Calculate the amount of Grown Stalk claimable by `account`.
        // Increase the account's balance of Stalk and Roots.
        __mow(account, token);

        // update lastUpdate for sop and germination calculations.
        s.a[account].lastUpdate = currentSeason;
    }

    /**
     * @dev Updates the mowStatus for the given account and token,
     * and mints Grown Stalk for the given account and token.
     */
    function __mow(
        address account,
        address token
    ) private {
        AppStorage storage s = LibAppStorage.diamondStorage();

        int96 _stemTip = LibTokenSilo.stemTipForToken(token);
        int96 _lastStem = s.a[account].mowStatuses[token].lastStem;
        uint128 _bdv = s.a[account].mowStatuses[token].bdv;

        // if:
        // 1: account has no bdv (new token deposit)
        // 2: the lastStem is the same as the stemTip (implying that a user has mowed),
        // then skip calculations to save gas.
        if (_bdv > 0) {
            if (_lastStem == _stemTip) {
                return;
            }

            // grown stalk does not germinate and is immediately included for bean mints.
            mintActiveStalk(account, _balanceOfGrownStalk(_lastStem, _stemTip, _bdv));
        }

        // If this `account` has no BDV, skip to save gas. Update lastStem.
        // (happen on initial deposit, since mow is called before any deposit)
        s.a[account].mowStatuses[token].lastStem = _stemTip;
        return;
    }

    /**
     * @notice returns the last season an account interacted with the silo.
     */
    function _lastUpdate(address account) internal view returns (uint32) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        return s.a[account].lastUpdate;
    }

    /**
     * @dev internal logic to handle when beanstalk is raining.
     */
    function handleRainAndSops(address account, uint32 lastUpdate, uint128 firstGerminatingRoots) private {
        AppStorage storage s = LibAppStorage.diamondStorage();
        // If a Sop has occured since last update, calculate rewards and set last Sop.
        if (s.season.lastSopSeason > lastUpdate) {
            s.a[account].sop.plenty = balanceOfPlenty(account);
            s.a[account].lastSop = s.season.lastSop;
        }
        // If no roots, reset Sop counters variables
        if (s.a[account].roots == 0) {
            s.a[account].lastSop = s.season.rainStart;
            s.a[account].lastRain = 0;
            return;
        }
        if (s.season.raining) {
            // If rain started after update, set account variables to track rain.
            if (s.season.rainStart > lastUpdate) {
                s.a[account].lastRain = s.season.rainStart;
                s.a[account].sop.roots = s.a[account].roots;
                if (s.season.rainStart - 1 == lastUpdate) {
                    if (firstGerminatingRoots > 0) {
                        // if the account had just finished germinating roots this season (i.e,
                        // deposited in the previous season before raining, and mowed during a sop),
                        // Beanstalk will not allocate plenty to this deposit, and thus the roots
                        // needs to be deducted from the sop roots.
                        s.a[account].sop.roots = s.a[account].sop.roots.sub(firstGerminatingRoots);
                    }
                }
                
                //  s.a[account].roots includes newly finished germinating roots from a fresh deposit
                //  @ season before rainStart
            }
            // If there has been a Sop since rain started,
            // save plentyPerRoot in case another SOP happens during rain.
            if (s.season.lastSop == s.season.rainStart) {
                s.a[account].sop.plentyPerRoot = s.sops[s.season.lastSop];
            }
        } else if (s.a[account].lastRain > 0) {
            // Reset Last Rain if not raining.
            s.a[account].lastRain = 0;
        }
    }

    /**
     * @dev returns the balance of amount of grown stalk based on stems.
     * @param lastStem the stem assoicated with the last mow
     * @param latestStem the current stem for a given token
     * @param bdv the bdv used to calculate grown stalk
     */
    function _balanceOfGrownStalk(
        int96 lastStem,
        int96 latestStem,
        uint128 bdv
    ) internal pure returns (uint256) {
        return stalkReward(lastStem, latestStem, bdv);
    }

    /**
     * @dev returns the amount of `plenty` an account has.
     */
    function balanceOfPlenty(address account) internal view returns (uint256 plenty) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        Account.State storage a = s.a[account];
        plenty = a.sop.plenty;
        uint256 previousPPR;

        // If lastRain > 0, then check if SOP occured during the rain period.
        if (s.a[account].lastRain > 0) {
            // if the last processed SOP = the lastRain processed season,
            // then we use the stored roots to get the delta.
            if (a.lastSop == a.lastRain) previousPPR = a.sop.plentyPerRoot;
            else previousPPR = s.sops[a.lastSop];
            uint256 lastRainPPR = s.sops[s.a[account].lastRain];

            // If there has been a SOP duing the rain sesssion since last update, process SOP.
            if (lastRainPPR > previousPPR) {
                uint256 plentyPerRoot = lastRainPPR - previousPPR;
                previousPPR = lastRainPPR;
                plenty = plenty.add(plentyPerRoot.mul(s.a[account].sop.roots).div(C.SOP_PRECISION));
            }
        } else {
            // If it was not raining, just use the PPR at previous SOP.
            previousPPR = s.sops[s.a[account].lastSop];
        }

        // Handle and SOPs that started + ended before after last Silo update.
        if (s.season.lastSop > _lastUpdate(account)) {
            uint256 plentyPerRoot = s.sops[s.season.lastSop].sub(previousPPR);
            plenty = plenty.add(plentyPerRoot.mul(s.a[account].roots).div(C.SOP_PRECISION));
        }
    }

    //////////////////////// REMOVE ////////////////////////

    /**
     * @dev Removes from a single Deposit, emits the RemoveDeposit event,
     * and returns the Stalk/BDV that were removed.
     *
     * Used in:
     * - {TokenSilo:_withdrawDeposit}
     * - {TokenSilo:_transferDeposit}
     */
    function _removeDepositFromAccount(
        address account,
        address token,
        int96 stem,
        uint256 amount,
        LibTokenSilo.Transfer transferType
    )
        internal
        returns (
            uint256 initialStalkRemoved,
            uint256 grownStalkRemoved,
            uint256 bdvRemoved,
            LibGerminate.Germinate germ
        )
    {
        AppStorage storage s = LibAppStorage.diamondStorage();
        int96 stemTip;
        (germ, stemTip) = LibGerminate.getGerminationState(token, stem);
        bdvRemoved = LibTokenSilo.removeDepositFromAccount(account, token, stem, amount);

        // the initial and grown stalk are seperated as there are instances
        // where the initial stalk issued for a deposit is germinating. Grown stalk never germinates,
        // and thus is not included in the germinating stalk.
        initialStalkRemoved = bdvRemoved.mul(s.ss[token].stalkIssuedPerBdv);

        grownStalkRemoved = stalkReward(stem, stemTip, bdvRemoved.toUint128());
        /**
         *  {_removeDepositFromAccount} is used for both withdrawing and transferring deposits.
         *  In the case of a withdraw, only the {TransferSingle} Event needs to be emitted.
         *  In the case of a transfer, a different {TransferSingle}/{TransferBatch}
         *  Event is emitted in {TokenSilo._transferDeposit(s)},
         *  and thus, this event is ommited.
         */
        if (transferType == LibTokenSilo.Transfer.emitTransferSingle) {
            // "removing" a deposit is equivalent to "burning" an ERC1155 token.
            emit LibTokenSilo.TransferSingle(
                msg.sender, // operator
                account, // from
                address(0), // to
                LibBytes.packAddressAndStem(token, stem), // depositid
                amount // token amount
            );
        }
        emit RemoveDeposit(account, token, stem, amount, bdvRemoved);
    }

    /**
     * @dev Removes from multiple Deposits, emits the RemoveDeposits
     * event, and returns the Stalk/BDV that were removed.
     *
     * Used in:
     * - {TokenSilo:_withdrawDeposits}
     * - {SiloFacet:enrootDeposits}
     *
     * @notice with the addition of germination, AssetsRemoved
     * keeps track of the germinating data.
     */
    function _removeDepositsFromAccount(
        address account,
        address token,
        int96[] calldata stems,
        uint256[] calldata amounts,
        ERC1155Event emission
    ) external returns (AssetsRemoved memory ar) {
        AppStorage storage s = LibAppStorage.diamondStorage();

        uint256[] memory bdvsRemoved = new uint256[](stems.length);
        uint256[] memory removedDepositIDs = new uint256[](stems.length);
        LibGerminate.GermStem memory germStem = LibGerminate.getGerminatingStem(token);
        for (uint256 i; i < stems.length; ++i) {
            LibGerminate.Germinate germState = LibGerminate._getGerminationState(
                stems[i],
                germStem
            );
            uint256 crateBdv = LibTokenSilo.removeDepositFromAccount(
                account,
                token,
                stems[i],
                amounts[i]
            );
            bdvsRemoved[i] = crateBdv;
            removedDepositIDs[i] = LibBytes.packAddressAndStem(token, stems[i]);
            uint256 crateStalk = stalkReward(stems[i], germStem.stemTip, crateBdv.toUint128());

            // if the deposit is germinating, decrement germinating values,
            // otherwise increment deposited values.
            if (germState == LibGerminate.Germinate.NOT_GERMINATING) {
                ar.active.bdv = ar.active.bdv.add(crateBdv);
                ar.active.stalk = ar.active.stalk.add(crateStalk);
                ar.active.tokens = ar.active.tokens.add(amounts[i]);
            } else {
                if (germState == LibGerminate.Germinate.ODD) {
                    ar.odd.bdv = ar.odd.bdv.add(crateBdv);
                    ar.odd.tokens = ar.odd.tokens.add(amounts[i]);
                } else {
                    ar.even.bdv = ar.even.bdv.add(crateBdv);
                    ar.even.tokens = ar.even.tokens.add(amounts[i]);
                }
                // grown stalk from germinating deposits do not germinate,
                // and thus must be added to the grown stalk.
                ar.grownStalkFromGermDeposits = ar.grownStalkFromGermDeposits.add(
                    crateStalk
                );
            }
        }

        // add initial stalk deposit to all stalk removed.
        {
            uint256 stalkIssuedPerBdv = s.ss[token].stalkIssuedPerBdv;
            if (ar.active.tokens > 0) {
                ar.active.stalk = ar.active.stalk.add(ar.active.bdv.mul(stalkIssuedPerBdv));
            }

            if (ar.odd.tokens > 0) {
                ar.odd.stalk = ar.odd.bdv.mul(stalkIssuedPerBdv);
            }

            if (ar.even.tokens > 0) {
                ar.even.stalk = ar.even.bdv.mul(stalkIssuedPerBdv);
            }
        }

        // "removing" deposits is equivalent to "burning" a batch of ERC1155 tokens.
        if (emission == ERC1155Event.EMIT_BATCH_EVENT) {
            emit TransferBatch(msg.sender, account, address(0), removedDepositIDs, amounts);
        }

        emit RemoveDeposits(
            account, 
            token, 
            stems, 
            amounts,
            ar.active.tokens.add(ar.odd.tokens).add(ar.even.tokens), 
            bdvsRemoved
        );
    }

    //////////////////////// UTILITIES ////////////////////////

    /**
     * @notice Calculates the Stalk reward based on the start and end
     * stems, and the amount of BDV deposited. Stems represent the
     * amount of grown stalk per BDV, so the difference between the
     * start index and end index (stem) multiplied by the amount of
     * bdv deposited will give the amount of stalk earned.
     * formula: stalk = bdv * (ΔstalkPerBdv)
     * 
     * @dev endStem must be larger than startStem.
     * 
     */
    function stalkReward(
        int96 startStem,
        int96 endStem,
        uint128 bdv
    ) internal pure returns (uint256) {
        uint128 reward = uint128(endStem.sub(startStem)).mul(bdv).div(PRECISION);

        return reward;
    }

    /**
     * @dev check whether the account needs to be migrated.
     */
    function migrationNeeded(address account) internal view returns (bool needsMigration, uint32 lastUpdate) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        lastUpdate = s.a[account].lastUpdate;
        needsMigration = lastUpdate > 0 && lastUpdate < s.season.stemStartSeason;
    }

    /**
     * @dev Internal function to compute `account` balance of Earned Beans.
     *
     * The number of Earned Beans is equal to the difference between:
     *  - the "expected" Stalk balance, determined from the account balance of
     *    Roots.
     *  - the "account" Stalk balance, stored in account storage.
     * divided by the number of Stalk per Bean.
     * The earned beans from the latest season
     */
    function _balanceOfEarnedBeans(
        uint256 accountStalk,
        uint256 accountRoots
    ) internal view returns (uint256 beans) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        // There will be no Roots before the first Deposit is made.
        if (s.s.roots == 0) return 0;

        uint256 stalk = s.s.stalk.mul(accountRoots).div(s.s.roots);

        // Beanstalk rounds down when minting Roots. Thus, it is possible that
        // balanceOfRoots / totalRoots * totalStalk < s.a[account].s.stalk.
        // As `account` Earned Balance balance should never be negative,
        // Beanstalk returns 0 instead.
        if (stalk <= accountStalk) return 0;

        // Calculate Earned Stalk and convert to Earned Beans.
        beans = (stalk - accountStalk).div(C.STALK_PER_BEAN); // Note: SafeMath is redundant here.
        if (beans > s.earnedBeans) return s.earnedBeans;

        return beans;
    }

    /**
     * @notice performs a one time update for the
     * users lastStem for all silo Tokens.
     * @dev Due to siloV3.1 update.
     */
    function migrateStems(address account) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        address[] memory siloTokens = LibWhitelistedTokens.getSiloTokens();
        for(uint i; i < siloTokens.length; i++) {
            // scale lastStem by 1e6, if the user has a lastStem.
            if (s.a[account].mowStatuses[siloTokens[i]].lastStem > 0) { 
                s.a[account].mowStatuses[siloTokens[i]].lastStem = 
                    s.a[account].mowStatuses[siloTokens[i]].lastStem.mul(int96(PRECISION));
            }
        }
    }

    /**
     * @dev An edge case can occur with the siloV3.1 update, where
     * A user updates their silo in the same season as the seedGauge update,
     * but prior to the seedGauge BIP execution (i.e the farmer mowed at the start of
     * the season, and the BIP was excuted mid-way through the season).
     * This function checks for that edge case and returns a boolean.
     */
    function checkStemEdgeCase(address account) internal view returns (bool) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        address[] memory siloTokens = LibWhitelistedTokens.getSiloTokens();
        // for each silo token, divide the stemTip of the token with the users last stem.
        // if the answer is 1e6 or greater, the user has not updated.
        for(uint i; i < siloTokens.length; i++) {
            int96 lastStem = s.a[account].mowStatuses[siloTokens[i]].lastStem;
            if (lastStem > 0) {
                if (LibTokenSilo.stemTipForToken(siloTokens[i]).div(lastStem) >= int96(PRECISION)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * @notice Returns the amount of Germinating Stalk 
     * for a given Germinate enum.
     * @dev When a Farmer attempts to withdraw Beans from a Deposit that has a Germinating Stem,
     * `checkForEarnedBeans` is called to determine how many of the Beans were Planted vs Deposited.
     * If a Farmer withdraws a Germinating Deposit with Earned Beans, only subtract the Germinating Beans
     * from the Germinating Balances
     * @return germinatingStalk stalk that is germinating for a given Germinate enum.
     * @return earnedBeanStalk the earned bean portion of stalk for a given Germinate enum.
     */
    function checkForEarnedBeans(
        address account,
        uint256 stalk,
        LibGerminate.Germinate germ
    ) internal view returns (uint256 germinatingStalk, uint256 earnedBeanStalk) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 farmerGerminatingStalk;
        if (germ == LibGerminate.Germinate.ODD) {
            farmerGerminatingStalk = s.a[account].farmerGerminating.odd;
        } else {
            farmerGerminatingStalk = s.a[account].farmerGerminating.even;
        }
        if (stalk > farmerGerminatingStalk) {
            return (farmerGerminatingStalk, stalk.sub(farmerGerminatingStalk));
        } else {
            return (stalk, 0);
        }
    }
}

File 27 of 28 : LibTokenSilo.sol
/**
 * SPDX-License-Identifier: MIT
 **/

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol";
import {LibAppStorage, Storage, AppStorage, Account} from "../LibAppStorage.sol";
import {C} from "../../C.sol";
import {LibSafeMath32} from "contracts/libraries/LibSafeMath32.sol";
import {LibSafeMath128} from "contracts/libraries/LibSafeMath128.sol";
import {LibSafeMathSigned128} from "contracts/libraries/LibSafeMathSigned128.sol";
import {LibSafeMathSigned96} from "contracts/libraries/LibSafeMathSigned96.sol";
import {LibBytes} from "contracts/libraries/LibBytes.sol";
import {LibGerminate} from "contracts/libraries/Silo/LibGerminate.sol";
import {LibWhitelistedTokens} from "contracts/libraries/Silo/LibWhitelistedTokens.sol";

/**
 * @title LibTokenSilo
 * @author Publius, Pizzaman1337
 * @notice Contains functions for depositing, withdrawing and claiming
 * whitelisted Silo tokens.
 *
 * For functionality related to Stalk, and Roots, see {LibSilo}.
 */
library LibTokenSilo {
    using SafeMath for uint256;
    using LibSafeMath128 for uint128;
    using LibSafeMath32 for uint32;
    using LibSafeMathSigned128 for int128;
    using SafeCast for int128;
    using SafeCast for uint256;
    using LibSafeMathSigned96 for int96;

    uint256 constant PRECISION = 1e6; // increased precision from to silo v3.1.


    //////////////////////// ENUM ////////////////////////
    /**
     * @dev when a user deposits or withdraws a deposit, the
     * {TrasferSingle} event is emitted. However, in the case
     * of a transfer, this emission is ommited. This enum is
     * used to determine if the event should be emitted.
     */
    enum Transfer {
        emitTransferSingle,
        noEmitTransferSingle
    }

    //////////////////////// EVENTS ////////////////////////

    /**
     * @dev IMPORTANT: copy of {TokenSilo-AddDeposit}, check there for details.
     */
    event AddDeposit(
        address indexed account,
        address indexed token,
        int96 stem,
        uint256 amount,
        uint256 bdv
    );

    /**
     * @dev IMPORTANT: copy of {TokenSilo-RemoveDeposit}, check there for details.
     */
    event RemoveDeposit(
        address indexed account,
        address indexed token,
        int96 stem,
        uint256 amount,
        uint256 bdv
    );

    // added as the ERC1155 deposit upgrade
    event TransferSingle(
        address indexed operator,
        address indexed sender,
        address indexed recipient,
        uint256 depositId,
        uint256 amount
    );

    //////////////////////// ACCOUNTING: TOTALS GERMINATING ////////////////////////

    /**
     * @notice Increment the total amount and bdv of `token` germinating in the Silo.
     * @dev when an asset is `deposited` in the silo, it is not immediately eliable for
     * bean mints. It must `germinate` (stay deposited the silo) for a certain
     * amount of seasons (the remainer of the current season + 1). This function
     * increments the total amount and bdv germinating in the silo. The {sunrise}
     * function ends the germination process for even or odd germinating deposits.
     *
     * This protects beanstalk from flashloan attacks, and makes `totalDeposited` and
     * `totalDepositedBdv` significantly more MEV resistant.
     */
    function incrementTotalGerminating(
        address token,
        uint256 amount,
        uint256 bdv,
        LibGerminate.Germinate germ
    ) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        Storage.TotalGerminating storage germinate;

        // verify germ is valid
        if (germ == LibGerminate.Germinate.ODD) {
            germinate = s.oddGerminating;
        } else if (germ == LibGerminate.Germinate.EVEN) {
            germinate = s.evenGerminating;
        } else {
            revert("invalid germinationMode"); // should not ever get here
        }

        // increment germinating amount and bdv.
        germinate.deposited[token].amount = germinate.deposited[token].amount.add(
            amount.toUint128()
        );
        germinate.deposited[token].bdv = germinate.deposited[token].bdv.add(bdv.toUint128());

        // emit event.
        emit LibGerminate.TotalGerminatingBalanceChanged(
            s.season.current,
            token,
            int256(amount),
            int256(bdv)
        );
    }

    /**
     * @notice Decrement the total amount and bdv of `token` germinating in the Silo.
     * @dev `decrementTotalGerminating` should be used when removing deposits
     * that are < 2 seasons old.
     */
    function decrementTotalGerminating(
        address token,
        uint256 amount,
        uint256 bdv,
        LibGerminate.Germinate germ
    ) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        Storage.TotalGerminating storage germinate;

        // verify germ is valid
        if (germ == LibGerminate.Germinate.ODD) {
            germinate = s.oddGerminating;
        } else if (germ == LibGerminate.Germinate.EVEN) {
            germinate = s.evenGerminating;
        } else {
            revert("invalid germinationMode"); // should not ever get here
        }

        // decrement germinating amount and bdv.
        germinate.deposited[token].amount = germinate.deposited[token].amount.sub(
            amount.toUint128()
        );
        germinate.deposited[token].bdv = germinate.deposited[token].bdv.sub(bdv.toUint128());
    
        emit LibGerminate.TotalGerminatingBalanceChanged(
            LibGerminate.getSeasonGerminationState() == germ ? 
                s.season.current : 
                s.season.current - 1,
            token,
            -int256(amount),
            -int256(bdv)
        );
    }

    /**
     * @notice Increment the total bdv of `token` germinating in the Silo. Used in Enroot.
     */
    function incrementTotalGerminatingBdv(
        address token,
        uint256 bdv,
        LibGerminate.Germinate germ
    ) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();

        if (germ == LibGerminate.Germinate.ODD) {
            // increment odd germinating
            s.oddGerminating.deposited[token].bdv = s.oddGerminating.deposited[token].bdv.add(
                bdv.toUint128()
            );
        } else if (germ == LibGerminate.Germinate.EVEN) {
            // increment even germinating
            s.evenGerminating.deposited[token].bdv = s.evenGerminating.deposited[token].bdv.add(
                bdv.toUint128()
            );
        } else {
            revert("invalid germinationMode"); // should not ever get here
        }

        emit LibGerminate.TotalGerminatingBalanceChanged(
            LibGerminate.getSeasonGerminationState() == germ ? 
                s.season.current : 
                s.season.current - 1,
            token,
            0,
            int256(bdv)
        );
    }

    //////////////////////// ACCOUNTING: TOTALS ////////////////////////

    /**
     * @dev Increment the total amount and bdv of `token` deposited in the Silo.
     * @dev `IncrementTotalDeposited` should be used when removing deposits that are
     * >= 2 seasons old (ex. when a user converts).
     */
    function incrementTotalDeposited(address token, uint256 amount, uint256 bdv) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        s.siloBalances[token].deposited = s.siloBalances[token].deposited.add(amount.toUint128());
        s.siloBalances[token].depositedBdv = s.siloBalances[token].depositedBdv.add(
            bdv.toUint128()
        );
    }

    /**
     * @notice Decrement the total amount and bdv of `token` deposited in the Silo.
     * @dev `decrementTotalDeposited` should be used when removing deposits that are
     * >= 2 seasons old.
     */
    function decrementTotalDeposited(address token, uint256 amount, uint256 bdv) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        s.siloBalances[token].deposited = s.siloBalances[token].deposited.sub(amount.toUint128());
        s.siloBalances[token].depositedBdv = s.siloBalances[token].depositedBdv.sub(
            bdv.toUint128()
        );
    }

    /**
     * @notice Increment the total bdv of `token` deposited in the Silo. Used in Enroot.
     */
    function incrementTotalDepositedBdv(address token, uint256 bdv) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        s.siloBalances[token].depositedBdv = s.siloBalances[token].depositedBdv.add(
            bdv.toUint128()
        );
    }

    //////////////////////// ADD DEPOSIT ////////////////////////

    /**
     * @return stalk The amount of Stalk received for this Deposit.
     *
     * @dev Calculate the current BDV for `amount` of `token`, then perform
     * Deposit accounting.
     */
    function deposit(
        address account,
        address token,
        int96 stem,
        uint256 amount
    ) internal returns (uint256, LibGerminate.Germinate) {
        uint256 bdv = beanDenominatedValue(token, amount);
        return depositWithBDV(account, token, stem, amount, bdv);
    }

    /**
     * @dev Once the BDV received for Depositing `amount` of `token` is known,
     * add a Deposit for `account` and update the total amount Deposited.
     *
     * `s.ss[token].stalkIssuedPerBdv` stores the number of Stalk per BDV for `token`.
     */
    function depositWithBDV(
        address account,
        address token,
        int96 stem,
        uint256 amount,
        uint256 bdv
    ) internal returns (uint256 stalk, LibGerminate.Germinate germ) {
        require(bdv > 0, "Silo: No Beans under Token.");
        AppStorage storage s = LibAppStorage.diamondStorage();

        // determine whether the deposit is odd or even germinating
        germ = LibGerminate.getSeasonGerminationState();

        // all new deposits will increment total germination.
        incrementTotalGerminating(token, amount, bdv, germ);
        
        addDepositToAccount(
            account,
            token,
            stem,
            amount,
            bdv,
            Transfer.emitTransferSingle
        );

        stalk = bdv.mul(s.ss[token].stalkIssuedPerBdv);
    }

    /**
     * @dev Add `amount` of `token` to a user's Deposit in `stemTipForToken`. Requires a
     * precalculated `bdv`.
     *
     * If a Deposit doesn't yet exist, one is created. Otherwise, the existing
     * Deposit is updated.
     *
     * `amount` & `bdv` are downcasted uint256 -> uint128 to optimize storage cost,
     * since both values can be packed into one slot.
     *
     * Unlike {removeDepositFromAccount}, this function DOES EMIT an
     * {AddDeposit} event. See {removeDepositFromAccount} for more details.
     */
    function addDepositToAccount(
        address account,
        address token,
        int96 stem,
        uint256 amount,
        uint256 bdv,
        Transfer transferType
    ) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 depositId = LibBytes.packAddressAndStem(token, stem);

        // add amount and bdv to the deposits.
        s.a[account].deposits[depositId].amount = s.a[account].deposits[depositId].amount.add(
            amount.toUint128()
        );
        s.a[account].deposits[depositId].bdv = s.a[account].deposits[depositId].bdv.add(
            bdv.toUint128()
        );

        // SafeMath unnecessary b/c crateBDV <= type(uint128).max
        s.a[account].mowStatuses[token].bdv = s.a[account].mowStatuses[token].bdv.add(
            bdv.toUint128()
        );

        /**
         *  {addDepositToAccount} is used for both depositing and transferring deposits.
         *  In the case of a deposit, only the {TransferSingle} Event needs to be emitted.
         *  In the case of a transfer, a different {TransferSingle}/{TransferBatch}
         *  Event is emitted in {TokenSilo._transferDeposit(s)},
         *  and thus, this event is ommited.
         */
        if (transferType == Transfer.emitTransferSingle) {
            emit TransferSingle(
                msg.sender, // operator
                address(0), // from
                account, // to
                depositId, // depositID
                amount // token amount
            );
        }
        emit AddDeposit(account, token, stem, amount, bdv);
    }

    //////////////////////// REMOVE DEPOSIT ////////////////////////

    /**
     * @dev Remove `amount` of `token` from a user's Deposit in `stem`.
     *
     * A "Crate" refers to the existing Deposit in storage at:
     *  `s.a[account].deposits[token][stem]`
     *
     * Partially removing a Deposit should scale its BDV proportionally. For ex.
     * removing 80% of the tokens from a Deposit should reduce its BDV by 80%.
     *
     * During an update, `amount` & `bdv` are cast uint256 -> uint128 to
     * optimize storage cost, since both values can be packed into one slot.
     *
     * This function DOES **NOT** EMIT a {RemoveDeposit} event. This
     * asymmetry occurs because {removeDepositFromAccount} is called in a loop
     * in places where multiple deposits are removed simultaneously, including
     * {TokenSilo-removeDepositsFromAccount} and {TokenSilo-_transferDeposits}.
     */

    function removeDepositFromAccount(
        address account,
        address token,
        int96 stem,
        uint256 amount
    ) internal returns (uint256 crateBDV) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 depositId = LibBytes.packAddressAndStem(token, stem);

        uint256 crateAmount = s.a[account].deposits[depositId].amount;
        crateBDV = s.a[account].deposits[depositId].bdv;
        // if amount is > crateAmount, check if user has a legacy deposit:
        if (amount > crateAmount) { 
            // get the absolute stem value.
            uint256 absStem = stem > 0 ? uint256(stem) : uint256(-stem);
            // only stems with modulo 1e6 can have a legacy deposit.
            if (absStem.mod(1e6) == 0) {
                (crateAmount, crateBDV) = migrateLegacyStemDeposit(
                    account,
                    token,
                    stem,
                    crateAmount,
                    crateBDV
                );
            }
        }
        require(amount <= crateAmount, "Silo: Crate balance too low.");

        // Partial remove
        if (amount < crateAmount) {
            // round up removal of BDV. (x - 1)/y + 1
            // https://stackoverflow.com/questions/17944
            uint256 removedBDV = amount.sub(1).mul(crateBDV).div(crateAmount).add(1);
            uint256 updatedBDV = crateBDV.sub(removedBDV);
            uint256 updatedAmount = crateAmount.sub(amount);

            // SafeCast unnecessary b/c updatedAmount <= crateAmount and updatedBDV <= crateBDV, 
            // which are both <= type(uint128).max
            s.a[account].deposits[depositId].amount = updatedAmount.toUint128();
            s.a[account].deposits[depositId].bdv = updatedBDV.toUint128();
            
            s.a[account].mowStatuses[token].bdv = s.a[account].mowStatuses[token].bdv.sub(
                removedBDV.toUint128()
            );

            return removedBDV;
        }
        // Full remove
        if (crateAmount > 0) delete s.a[account].deposits[depositId];

        // SafeMath unnecessary b/c crateBDV <= type(uint128).max
        s.a[account].mowStatuses[token].bdv = s.a[account].mowStatuses[token].bdv.sub(
            crateBDV.toUint128()
        );
    }

    //////////////////////// GETTERS ////////////////////////

    /**
     * @dev Calculate the BDV ("Bean Denominated Value") for `amount` of `token`.
     *
     * Makes a call to a BDV function defined in the SiloSettings for this
     * `token`. See {AppStorage.sol:Storage-SiloSettings} for more information.
     */
    function beanDenominatedValue(
        address token,
        uint256 amount
    ) internal view returns (uint256 bdv) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        require(s.ss[token].selector != bytes4(0), "Silo: Token not whitelisted");

        (bool success, bytes memory data) = address(this).staticcall(
            encodeBdvFunction(token, s.ss[token].encodeType, s.ss[token].selector, amount)
        );

        if (!success) {
            if (data.length == 0) revert();
            assembly {
                revert(add(32, data), mload(data))
            }
        }

        assembly {
            bdv := mload(add(data, add(0x20, 0)))
        }
    }

    function encodeBdvFunction(
        address token,
        bytes1 encodeType,
        bytes4 selector,
        uint256 amount
    ) internal pure returns (bytes memory callData) {
        if (encodeType == 0x00) {
            callData = abi.encodeWithSelector(selector, amount);
        } else if (encodeType == 0x01) {
            callData = abi.encodeWithSelector(selector, token, amount);
        } else {
            revert("Silo: Invalid encodeType");
        }
    }

    /**
     * @dev Locate the `amount` and `bdv` for a user's Deposit in storage.
     *
     * Silo V3 Deposits are stored within each {Account} as a mapping of:
     *  `uint256 DepositID => { uint128 amount, uint128 bdv }`
     *  The DepositID is the concatination of the token address and the stem.
     *
     * Silo V2 deposits are only usable after a successful migration, see
     * mowAndMigrate within the Migration facet.
     *
     */
    function getDeposit(
        address account,
        address token,
        int96 stem
    ) internal view returns (uint256 amount, uint256 bdv) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 depositId = LibBytes.packAddressAndStem(token, stem);
        amount = s.a[account].deposits[depositId].amount;
        bdv = s.a[account].deposits[depositId].bdv;
    }

    /**
     * @dev Get the number of Stalk per BDV per Season for a whitelisted token.
     * 6 decimal precision: 1e10 units = 1 stalk per season
     */
    function stalkEarnedPerSeason(address token) internal view returns (uint256) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        return uint256(s.ss[token].stalkEarnedPerSeason);
    }

    /**
     * @dev Get the number of Stalk per BDV for a whitelisted token. Formerly just stalk.
     */
    function stalkIssuedPerBdv(address token) internal view returns (uint256) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        return uint256(s.ss[token].stalkIssuedPerBdv);
    }

    /**
     * @dev returns the cumulative stalk per BDV (stemTip) for a whitelisted token.
     */
    function stemTipForToken(
        address token
    ) internal view returns (int96 _stemTip) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        // SafeCast unnecessary because all casted variables are types smaller that int96.
        _stemTip =
            s.ss[token].milestoneStem +
            int96(s.ss[token].stalkEarnedPerSeason).mul(
                int96(s.season.current).sub(int96(s.ss[token].milestoneSeason))
            );
    }

    /**
     * @dev returns the amount of grown stalk a deposit has earned.
     */
    function grownStalkForDeposit(
        address account,
        address token,
        int96 stem
    ) internal view returns (uint grownStalk) {
        // stemTipForToken(token) > depositGrownStalkPerBdv for all valid Deposits
        int96 _stemTip = stemTipForToken(token);
        require(stem <= _stemTip, "Silo: Invalid Deposit");
        // The check in the above line guarantees that subtraction result is positive
        // and thus the cast to `uint256` is safe.
        uint deltaStemTip = uint256(_stemTip.sub(stem));
        // no stalk has grown if the stem is equal to the stemTip.
        if (deltaStemTip == 0) return 0;
        (, uint bdv) = getDeposit(account, token, stem);

        grownStalk = deltaStemTip.mul(bdv).div(PRECISION);
    }

    /**
     * @dev returns the amount of grown stalk a deposit would have, based on the stem of the deposit.
     */
    function calculateStalkFromStemAndBdv(
        address token,
        int96 grownStalkIndexOfDeposit,
        uint256 bdv
    ) internal view returns (int96 grownStalk) {
        // current latest grown stalk index
        int96 _stemTipForToken = stemTipForToken(address(token));

        return _stemTipForToken.sub(grownStalkIndexOfDeposit).mul(toInt96(bdv));
    }

    /**
     * @notice returns the grown stalk and germination state of a deposit,
     * based on the amount of grown stalk it has earned.
     */
    function calculateStemForTokenFromGrownStalk(
        address token,
        uint256 grownStalk,
        uint256 bdv
    ) internal view returns (int96 stem, LibGerminate.Germinate germ) {
        LibGerminate.GermStem memory germStem = LibGerminate.getGerminatingStem(token);
        stem = germStem.stemTip.sub(toInt96(grownStalk.mul(PRECISION).div(bdv)));
        germ = LibGerminate._getGerminationState(stem, germStem);
    }

    /**
     * @dev returns the amount of grown stalk a deposit would have, based on the stem of the deposit.
     * Similar to calculateStalkFromStemAndBdv, but has an additional check to prevent division by 0.
     */
    function grownStalkAndBdvToStem(
        address token,
        uint256 grownStalk,
        uint256 bdv
    ) internal view returns (int96 cumulativeGrownStalk) {
        // first get current latest grown stalk index
        int96 _stemTipForToken = stemTipForToken(token);
        // then calculate how much stalk each individual bdv has grown
        // there's a > 0 check here, because if you have a small amount of unripe bean deposit, the bdv could
        // end up rounding to zero, then you get a divide by zero error and can't migrate without losing that deposit

        // prevent divide by zero error
        int96 grownStalkPerBdv = bdv > 0 ? toInt96(grownStalk.mul(PRECISION).div(bdv)) : 0;

        // subtract from the current latest index, so we get the index the deposit should have happened at
        return _stemTipForToken.sub(grownStalkPerBdv);
    }

    /**
     * @notice internal logic for migrating a legacy deposit.
     * @dev 
     */
    function migrateLegacyStemDeposit(
        address account, 
        address token,
        int96 newStem,
        uint256 crateAmount,
        uint256 crateBdv
    ) internal returns (uint256, uint256) { 
        AppStorage storage s = LibAppStorage.diamondStorage();
        // divide the newStem by 1e6 to get the legacy stem.
        uint256 legacyDepositId = LibBytes.packAddressAndStem(token, newStem.div(1e6));
        uint256 legacyAmount = s.a[account].legacyV3Deposits[legacyDepositId].amount;
        uint256 legacyBdv = s.a[account].legacyV3Deposits[legacyDepositId].bdv;
        crateAmount = crateAmount.add(legacyAmount);
        crateBdv = crateBdv.add(legacyBdv);
        delete s.a[account].legacyV3Deposits[legacyDepositId];

        // Emit burn events.
        emit TransferSingle(
            msg.sender,
            account,
            address(0),
            legacyDepositId,
            legacyAmount
        );

        emit RemoveDeposit(
            account,
            token,
            newStem.div(1e6),
            legacyAmount,
            legacyBdv
        );

        // Emit mint events.
        emit TransferSingle(
            msg.sender,
            address(0),
            account,
            LibBytes.packAddressAndStem(token, newStem),
            legacyAmount
        );

        emit AddDeposit(
            account,
            token,
            newStem,
            legacyAmount,
            legacyBdv
        );

        return (crateAmount, crateBdv);
    }

    function toInt96(uint256 value) internal pure returns (int96) {
        require(value <= uint256(type(int96).max), "SafeCast: value doesn't fit in an int96");
        return int96(value);
    }
}

File 28 of 28 : LibWhitelistedTokens.sol
/*
 SPDX-License-Identifier: MIT
*/

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import {C} from "../../C.sol";
import {AppStorage, Storage, LibAppStorage} from "contracts/libraries/LibAppStorage.sol";

/**
 * @title LibWhitelistedTokens
 * @author Brean, Brendan
 * @notice LibWhitelistedTokens holds different lists of types of Whitelisted Tokens.
 * 
 * @dev manages the WhitelistStatuses for all tokens in the Silo in order to track lists.
 * Note: dewhitelisting a token doesn't remove it's WhitelistStatus entirely–It just modifies it.
 * Once a token has no more Deposits in the Silo, it's WhitelistStatus should be removed through calling `removeWhitelistStatus`.
 */
library LibWhitelistedTokens {


    /** 
     * @notice Emitted when a Whitelis Status is added.
     */
    event AddWhitelistStatus(
        address token,
        uint256 index,
        bool isWhitelisted,
        bool isWhitelistedLp,
        bool isWhitelistedWell
    );

    /**
     * @notice Emitted when a Whitelist Status is removed.
     */
    event RemoveWhitelistStatus(
        address token,
        uint256 index
    );

    /**
     * @notice Emitted when a Whitelist Status is updated.
     */
    event UpdateWhitelistStatus(
        address token,
        uint256 index,
        bool isWhitelisted,
        bool isWhitelistedLp,
        bool isWhitelistedWell
    );

    /**
     * @notice Returns all tokens that are currently or previously in the silo, 
     * including Unripe tokens.
     * @dev includes Dewhitelisted tokens with existing Deposits.
     */
    function getSiloTokens() internal view returns (address[] memory tokens) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 numberOfSiloTokens = s.whitelistStatuses.length;

        tokens = new address[](numberOfSiloTokens);

        for (uint256 i = 0; i < numberOfSiloTokens; i++) {
            tokens[i] = s.whitelistStatuses[i].token;
        }
    }

    /**
     * @notice Returns the current Whitelisted tokens, including Unripe tokens.
     */
    function getWhitelistedTokens() internal view returns (address[] memory tokens) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 numberOfSiloTokens = s.whitelistStatuses.length;
        uint256 tokensLength;
    
        tokens = new address[](numberOfSiloTokens);

        for (uint256 i = 0; i < numberOfSiloTokens; i++) {
            if (s.whitelistStatuses[i].isWhitelisted) {
                tokens[tokensLength++] = s.whitelistStatuses[i].token;
            }
        }
        assembly {
            mstore(tokens, tokensLength)
        }
    }

    /**
     * @notice Returns the current Whitelisted LP tokens. 
     * @dev Unripe LP is not an LP token.
     */
    function getWhitelistedLpTokens() internal view returns (address[] memory tokens) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 numberOfSiloTokens = s.whitelistStatuses.length;
        uint256 tokensLength;

        tokens = new address[](numberOfSiloTokens);

        for (uint256 i = 0; i < numberOfSiloTokens; i++) {
            if (s.whitelistStatuses[i].isWhitelistedLp) {
                // assembly {
                //     mstore(tokens, add(mload(tokens), 1))
                // }
                tokens[tokensLength++] = s.whitelistStatuses[i].token;
            }
        }
        assembly {
            mstore(tokens, tokensLength)
        }
    }

    /**
     * @notice Returns the current Whitelisted Well LP tokens.
     */
    function getWhitelistedWellLpTokens() internal view returns (address[] memory tokens) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 numberOfSiloTokens = s.whitelistStatuses.length;
        uint256 tokensLength;

        tokens = new address[](numberOfSiloTokens);

        for (uint256 i = 0; i < numberOfSiloTokens; i++) {
            if (s.whitelistStatuses[i].isWhitelistedWell) {
                tokens[tokensLength++] = s.whitelistStatuses[i].token;
            }
        }
        assembly {
            mstore(tokens, tokensLength)
        }
    }

    /**
     * @notice Returns the Whitelist statues for all tokens that have been whitelisted and not manually removed.
     */
    function getWhitelistedStatuses() internal view returns (Storage.WhitelistStatus[] memory _whitelistStatuses) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        _whitelistStatuses = s.whitelistStatuses;
    }

    /**
     * @notice Returns the Whitelist status for a given token.
     */
    function getWhitelistedStatus(address token) internal view returns (Storage.WhitelistStatus memory _whitelistStatus) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 tokenStatusIndex = findWhitelistStatusIndex(token);
        _whitelistStatus = s.whitelistStatuses[tokenStatusIndex];
    }

    /**
     * @notice Adds a Whitelist Status for a given `token`.
     */
    function addWhitelistStatus(address token, bool isWhitelisted, bool isWhitelistedLp, bool isWhitelistedWell) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        s.whitelistStatuses.push(Storage.WhitelistStatus(
            token,
            isWhitelisted,
            isWhitelistedLp,
            isWhitelistedWell
        ));

        emit AddWhitelistStatus(token, s.whitelistStatuses.length - 1, isWhitelisted, isWhitelistedLp, isWhitelistedWell);
    }

    /**
     * @notice Modifies the exisiting Whitelist Status of `token`.
     */
    function updateWhitelistStatus(address token, bool isWhitelisted, bool isWhitelistedLp, bool isWhitelistedWell) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 tokenStatusIndex = findWhitelistStatusIndex(token);
        s.whitelistStatuses[tokenStatusIndex].isWhitelisted = isWhitelisted;
        s.whitelistStatuses[tokenStatusIndex].isWhitelistedLp = isWhitelistedLp;
        s.whitelistStatuses[tokenStatusIndex].isWhitelistedWell = isWhitelistedWell;

        emit UpdateWhitelistStatus(
            token,
            tokenStatusIndex,
            isWhitelisted,
            isWhitelistedLp,
            isWhitelistedWell
        );
    }

    /**
     * @notice Removes `token`'s Whitelist Status.
     */
    function removeWhitelistStatus(address token) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 tokenStatusIndex = findWhitelistStatusIndex(token);
        s.whitelistStatuses[tokenStatusIndex] = s.whitelistStatuses[s.whitelistStatuses.length - 1];
        s.whitelistStatuses.pop();

        emit RemoveWhitelistStatus(token, tokenStatusIndex);
    }

    /**
     * @notice Finds the index of a given `token`'s Whitelist Status.
     */
    function findWhitelistStatusIndex(address token) private view returns (uint256) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 whitelistedStatusLength = s.whitelistStatuses.length;
        uint256 i;
        while (s.whitelistStatuses[i].token != token) {
            i++;
            if (i >= whitelistedStatusLength) {
                revert("LibWhitelistedTokens: Token not found");
            }
        }
        return i;
    }

    /**
     * @notice checks if a token is whitelisted.
     * @dev checks whether a token is in the whitelistStatuses array. If it is,
     * verify whether `isWhitelisted` is set to false.
     * @param token the token to check.
     */
    function checkWhitelisted(address token) internal view returns (bool isWhitelisted, bool previouslyWhitelisted) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 whitelistedStatusLength = s.whitelistStatuses.length;
        uint256 i;
        while (s.whitelistStatuses[i].token != token) {
            i++;
            if (i >= whitelistedStatusLength) {
                // if the token does not appear in the array
                // it has not been whitelisted nor dewhitelisted.
                return (false, false);
            }
        }

        if (s.whitelistStatuses[i].isWhitelisted) {
            // token is whitelisted.
            return (true, false);
        } else {
            // token has been whitelisted previously.
            return (false, true);
        }
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 100
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"_uri","type":"string"},{"indexed":true,"internalType":"uint256","name":"_id","type":"uint256"}],"name":"URI","type":"event"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"int96","name":"stem","type":"int96"},{"internalType":"int96","name":"stemTip","type":"int96"}],"name":"imageURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"depositId","type":"uint256"}],"name":"uri","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"}]

608060405234801561001057600080fd5b50614f73806100206000396000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c806306fdde03146100515780630e89341c1461006f57806395d89b4114610082578063c20b80711461008a575b600080fd5b61005961009d565b6040516100669190613d62565b60405180910390f35b61005961007d3660046137bb565b6100ce565b610059610251565b61005961009836600461376c565b610272565b6040805180820190915260178152764265616e7374616c6b2053696c6f204465706f7369747360481b602082015290565b60606000806100dc8461031e565b9150915060006100eb8361032a565b6001600160a01b038416600090815260396020526040902054909150600160601b900463ffffffff1615801590610128575081600b0b81600b0b12155b61014d5760405162461bcd60e51b815260040161014490613d95565b60405180910390fd5b6000610158846103e2565b61016c856001600160a01b03166014610559565b610177886020610559565b61018386600b0b6106c1565b61019461018f89610761565b61079d565b6101a2888803600b0b61079d565b6101ae61018f8b610878565b6040516020016101c49796959493929190613987565b6040516020818303038152906040529050610226816101e4868686610272565b6040516020016101f49190613d1f565b60408051601f19818403018152908290526102129291602001613ad6565b6040516020818303038152906040526108b4565b6040516020016102369190613cda565b6040516020818303038152906040529450505050505b919050565b60408051808201909152600781526611115413d4d25560ca1b602082015290565b60606102876102828585856109f5565b6108b4565b60405160200180807f646174613a696d6167652f7376672b786d6c3b6261736536342c000000000000815250601a0182805190602001908083835b602083106102e15780518252601f1990920191602091820191016102c2565b6001836020036101000a03801982511681845116808217855250505050505090500191505060405160208183030381529060405290509392505050565b606081901c815b915091565b600080610335610b82565b6001600160a01b038416600090815260398201602052604090205460038201549192506103b29161037d9163ffffffff918216600b0b91600160601b909104811690610b8716565b6001600160a01b038516600090815260398401602052604090205463ffffffff600160201b9091048116600b0b9190610bff16565b6001600160a01b03909316600090815260399091016020526040902054600160801b9004600b0b91909101919050565b60606001600160a01b038216731bea3ccd22f4ebd3d37d731ba31eeca95713716d141561042e5750604080518082019091526008815267075724245414e4c560c41b602082015261024c565b816001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b15801561046757600080fd5b505afa15801561047b573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405260208110156104a457600080fd5b8101908080516040519392919084600160201b8211156104c357600080fd5b9083019060208201858111156104d857600080fd5b8251600160201b8111828201881017156104f157600080fd5b82525081516020918201929091019080838360005b8381101561051e578181015183820152602001610506565b50505050905090810190601f16801561054b5780820380516001836020036101000a031916815260200191505b506040525050509050919050565b606060008260020260020167ffffffffffffffff8111801561057a57600080fd5b506040519080825280601f01601f1916602001820160405280156105a5576020820181803683370190505b509050600360fc1b816000815181106105ba57fe5b60200101906001600160f81b031916908160001a905350600f60fb1b816001815181106105e357fe5b60200101906001600160f81b031916908160001a905350600160028402015b6001811115610664576f181899199a1a9b1b9c1cb0b131b232b360811b85600f166010811061062d57fe5b1a60f81b82828151811061063d57fe5b60200101906001600160f81b031916908160001a90535060049490941c9360001901610602565b5083156106b8576040805162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e74604482015290519081900360640190fd5b90505b92915050565b606060008213156106dc576106d58261079d565b905061024c565b6106e88260000361079d565b6040516020018080602d60f81b81525060010182805190602001908083835b602083106107265780518252601f199092019160209182019101610707565b6001836020036101000a038019825116818451168082178552505050505050905001915050604051602081830303815290604052905061024c565b60008061076c610b82565b6001600160a01b0393909316600090815260399390930160205250506040902054600160401b900463ffffffff1690565b6060816107c257506040805180820190915260018152600360fc1b602082015261024c565b8160005b81156107da57600101600a820491506107c6565b60008167ffffffffffffffff811180156107f357600080fd5b506040519080825280601f01601f19166020018201604052801561081e576020820181803683370190505b50859350905060001982015b831561086f57600a840660300160f81b8282806001900393508151811061084d57fe5b60200101906001600160f81b031916908160001a905350600a8404935061082a565b50949350505050565b600080610883610b82565b6001600160a01b0393909316600090815260399390930160205250506040902054600160201b900463ffffffff1690565b60608151600014156108d5575060408051602081019091526000815261024c565b60006040518060600160405280604081526020016148296040913990506000600384516002018161090257fe5b0460040267ffffffffffffffff8111801561091c57600080fd5b506040519080825280601f01601f191660200182016040528015610947576020820181803683370190505b509050600182016020820185865187015b808210156109b3576003820191508151603f8160121c168501518453600184019350603f81600c1c168501518453600184019350603f8160061c168501518453600184019350603f8116850151845350600183019250610958565b50506003865106600181146109cf57600281146109e2576109ea565b603d6001830353603d60028303536109ea565b603d60018303535b509195945050505050565b6060828203610a0381610ccf565b610a0b610fbf565b610a1483611005565b610a1e8888611094565b604051602001806092614e83823960920185805190602001908083835b60208310610a5a5780518252601f199092019160209182019101610a3b565b51815160209384036101000a600019018019909216911617905287519190930192870191508083835b60208310610aa25780518252601f199092019160209182019101610a83565b51815160209384036101000a600019018019909216911617905286519190930192860191508083835b60208310610aea5780518252601f199092019160209182019101610acb565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b60208310610b325780518252601f199092019160209182019101610b13565b5181516020939093036101000a6000190180199091169216919091179052651e17b9bb339f60d11b92019182525060408051808303601919018152600690920190529a9950505050505050505050565b600090565b6000818303600b83900b8213801590610ba6575083600b0b81600b0b13155b80610bc45750600083600b0b128015610bc4575083600b0b81600b0b135b6106b85760405162461bcd60e51b8152600401808060200182810382526024815260200180614d706024913960400191505060405180910390fd5b600082600b0b60001415610c15575060006106bb565b82600b0b600019148015610c395750600b82900b6b7fffffffffffffffffffffff19145b15610c755760405162461bcd60e51b8152600401808060200182810382526027815260200180614b9b6027913960400191505060405180910390fd5b6000828402905082600b0b84600b0b82600b0b81610c8f57fe5b05600b0b146106b85760405162461bcd60e51b8152600401808060200182810382526027815260200180614b9b6027913960400191505060405180910390fd5b60606000610cdc836111eb565b5090506000610cec82600461123f565b9050610cf66112a1565b610cfe611304565b610d06611622565b610d0f846116e5565b610d18886118b9565b610d2061212a565b610d2861217c565b610d30612213565b6040516020018080651e3232b3399f60d11b81525060060189805190602001908083835b60208310610d735780518252601f199092019160209182019101610d54565b51815160209384036101000a60001901801990921691161790528b5191909301928b0191508083835b60208310610dbb5780518252601f199092019160209182019101610d9c565b51815160209384036101000a60001901801990921691161790528a5191909301928a0191508083835b60208310610e035780518252601f199092019160209182019101610de4565b51815160209384036101000a600019018019909216911617905289519190930192890191508083835b60208310610e4b5780518252601f199092019160209182019101610e2c565b51815160209384036101000a600019018019909216911617905288519190930192880191508083835b60208310610e935780518252601f199092019160209182019101610e74565b51815160209384036101000a600019018019909216911617905287519190930192870191508083835b60208310610edb5780518252601f199092019160209182019101610ebc565b51815160209384036101000a600019018019909216911617905286519190930192860191508083835b60208310610f235780518252601f199092019160209182019101610f04565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b60208310610f6b5780518252601f199092019160209182019101610f4c565b5181516020939093036101000a6000190180199091169216919091179052661e17b232b3399f60c91b92019182525060408051808303601819018152600790920190529d9c50505050505050505050505050565b60606040516020018080614b13602d91396611991a9999991b60c91b602d8201526211179f60e91b60348201526040805160178184030181526037909201905291505090565b606061101082612283565b604051602001806054614d94823960540182805190602001908083835b6020831061104c5780518252601f19909201916020918201910161102d565b5181516020939093036101000a6000190180199091169216919091179052631e17b39f60e11b92019182525060408051808303601b1901815260049092019052949350505050565b606061109f8361298b565b6110a884612a1d565b6110b184612b44565b604051602001806041614be2823960410184805190602001908083835b602083106110ed5780518252601f1990920191602091820191016110ce565b6001836020036101000a03801982511681845116808217855250505050505090500180614c236043913960430183805190602001908083835b602083106111455780518252601f199092019160209182019101611126565b6001836020036101000a038019825116818451168082178552505050505050905001806146b26060913960600182805190602001908083835b6020831061119d5780518252601f19909201916020918201910161117e565b5181516020939093036101000a6000190180199091169216919091179052661e17ba32bc3a1f60c91b9201918252506040805180830360181901815260079092019052979650505050505050565b600080611200600b84900b630bebc200612ba3565b91506112186001611212846010612ba3565b90612c0a565b9050600061122783601061123f565b111561032557611238816001612c0a565b9050915091565b6000808211611290576040805162461bcd60e51b8152602060048201526018602482015277536166654d6174683a206d6f64756c6f206279207a65726f60401b604482015290519081900360640190fd5b81838161129957fe5b069392505050565b6040516c1e339034b21e91383637ba111f60991b60208201908152606091602d01606c613f458239606c0180614794606c9139606c0160686145478239631e17b39f60e11b606882015260408051604c818403018152606c909201905291505090565b6060611330604051806040016040528060048152602001631c1b1bdd60e21b8152506022196000612c64565b61137d604051806040016040528060078152602001666c656166526f7760c81b8152506022196000604051806040016040528060078152602001662341384338334160c81b815250612ddc565b6113ca604051806040016040528060078152602001666c656166526f7760c81b815250602e19600760405180604001604052806007815260200166119c1ca09b192360c91b815250612ddc565b611417604051806040016040528060078152602001666c656166526f7760c81b815250603b19600e604051806040016040528060078152602001662341384338334160c81b815250612ddc565b611464604051806040016040528060078152602001666c656166526f7760c81b815250604819601560405180604001604052806007815260200166119c1ca09b192360c91b815250612ddc565b6040516020018080741e339034b21e91333ab6362632b0b3283637ba111f60591b81525060150186805190602001908083835b602083106114b65780518252601f199092019160209182019101611497565b51815160209384036101000a600019018019909216911617905288519190930192880191508083835b602083106114fe5780518252601f1990920191602091820191016114df565b51815160209384036101000a600019018019909216911617905287519190930192870191508083835b602083106115465780518252601f199092019160209182019101611527565b51815160209384036101000a600019018019909216911617905286519190930192860191508083835b6020831061158e5780518252601f19909201916020918201910161156f565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b602083106115d65780518252601f1990920191602091820191016115b7565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b81525060040195505050505050604051602081830303815290604052905090565b606061164e604051806040016040528060048152602001631c1b1bdd60e21b8152506022196000612c64565b6040516020018080711e339034b21e9132b6b83a3ca83637ba111f60711b81525060120182805190602001908083835b6020831061169d5780518252601f19909201916020918201910161167e565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b815250600401915050604051602081830303815290604052905090565b606081611729575060408051600080516020614bc28339815191526020820152631e17b39f60e11b60378201528151601b818303018152603b90910190915261024c565b816001141561178057604051600080516020614bc28339815191526020820190815290603701602561466d823960250180631e17b39f60e11b8152506004019050604051602081830303815290604052905061024c565b81600214156117e157604051600080516020614bc28339815191526020820190815290603701602561466d82396025016028614712823960280180631e17b39f60e11b8152506004019050604051602081830303815290604052905061024c565b816003141561184c57604051600080516020614bc28339815191526020820190815290603701602561466d8239602501602861471282396028016029614800823960290180631e17b39f60e11b8152506004019050604051602081830303815290604052905061024c565b604051600080516020614bc28339815191526020820190815290603701602561466d8239602501602861471282396028016029614800823960290180614f156029913960290180631e17b39f60e11b8152506004019050604051602081830303815290604052905061024c565b606060006118d46010611212600b86900b630bebc200612ba3565b905060006118ed60046118e78482612ba3565b9061123f565b905060006118fc83600461123f565b905081611b8e578015611a6257611933604051806040016040528060048152602001631c1b1bdd60e21b8152506022196000612c64565b6119876040518060400160405280600e81526020016d7061727469616c4c656166526f7760901b8152506022196000604051806040016040528060078152602001662341384338334160c81b815250612ddc565b604051602001808060008051602061469283398151915281525060180183805190602001908083835b602083106119cf5780518252601f1990920191602091820191016119b0565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b60208310611a175780518252601f1990920191602091820191016119f8565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b815250600401925050506040516020818303038152906040529350611b8e565b611a6a612fb3565b611ab7604051806040016040528060078152602001666c656166526f7760c81b815250604819601560405180604001604052806007815260200166119c1ca09b192360c91b815250612ddc565b604051602001808060008051602061469283398151915281525060180183805190602001908083835b60208310611aff5780518252601f199092019160209182019101611ae0565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b60208310611b475780518252601f199092019160209182019101611b28565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b8152506004019250505060405160208183030381529060405293505b8160011415611d6a578015611cd457611ba56130be565b611bf96040518060400160405280600e81526020016d7061727469616c4c656166526f7760901b815250602e19600760405180604001604052806007815260200166119c1ca09b192360c91b815250612ddc565b604051602001808060008051602061469283398151915281525060180183805190602001908083835b60208310611c415780518252601f199092019160209182019101611c22565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b60208310611c895780518252601f199092019160209182019101611c6a565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b815250600401925050506040516020818303038152906040529350611d6a565b611cdc6130be565b604051602001808060008051602061469283398151915281525060180182805190602001908083835b60208310611d245780518252601f199092019160209182019101611d05565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b81525060040191505060405160208183030381529060405293505b8160021415611f46578015611eb057611d81613137565b611dd56040518060400160405280600e81526020016d7061727469616c4c656166526f7760901b815250603b19600e604051806040016040528060078152602001662341384338334160c81b815250612ddc565b604051602001808060008051602061469283398151915281525060180183805190602001908083835b60208310611e1d5780518252601f199092019160209182019101611dfe565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b60208310611e655780518252601f199092019160209182019101611e46565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b815250600401925050506040516020818303038152906040529350611f46565b611eb8613137565b604051602001808060008051602061469283398151915281525060180182805190602001908083835b60208310611f005780518252601f199092019160209182019101611ee1565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b81525060040191505060405160208183030381529060405293505b816003141561212257801561208c57611f5d612fb3565b611fb16040518060400160405280600e81526020016d7061727469616c4c656166526f7760901b815250604819601560405180604001604052806007815260200166119c1ca09b192360c91b815250612ddc565b604051602001808060008051602061469283398151915281525060180183805190602001908083835b60208310611ff95780518252601f199092019160209182019101611fda565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b602083106120415780518252601f199092019160209182019101612022565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b815250600401925050506040516020818303038152906040529350612122565b612094612fb3565b604051602001808060008051602061469283398151915281525060180182805190602001908083835b602083106120dc5780518252601f1990920191602091820191016120bd565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b81525060040191505060405160208183030381529060405293505b505050919050565b6040516c1e339034b21e913632b0b3111f60991b60208201908152606091602d01610339613fb18239631e17b39f60e11b6103398201526040805161031d81840301815261033d909201905291505090565b6040516c1e339034b21e9139b4b637911f60991b60208201908152606091602d0160be6145af823960be016101b961438e82396101b90160ae613e97823960ae01609b614de88239609b0160da614915823960da0161010a614c66823961010a0160a46142ea823960a401605161486982396051016101246149ef8239610124019050604051602081830303815290604052905090565b6040516f1e339034b21e913632b0b32937bb911f60811b60208201908152606091603001602561466d8239602501602861471282396028016029614800823960290180614f1560299139631e17b39f60e11b602982015260408051600d818403018152602d909201905291505090565b60606000604051806102a001604052806040518060400160405280604419815260200160a319815250815260200160405180604001604052806045815260200160a3198152508152602001604051806040016040528060008152602001607b1981525081526020016040518060400160405280608a8152602001607b19815250815260200160405180604001604052806089198152602001607b198152508152602001604051806040016040528060441981526020016053198152508152602001604051806040016040528060458152602001605319815250815260200160405180604001604052806089198152602001602b198152508152602001604051806040016040528060008152602001602b1981525081526020016040518060400160405280608a8152602001602b198152508152602001604051806040016040528060441981526020016003198152508152602001604051806040016040528060458152602001600319815250815260200160405180604001604052806089198152602001602481525081526020016040518060400160405280608a81526020016024815250815260200160405180604001604052806044198152602001604c8152508152602001604051806040016040528060458152602001604c81525081526020016040518060400160405280608919815260200160748152508152602001604051806040016040528060008152602001607481525081526020016040518060400160405280608a815260200160748152508152602001604051806040016040528060458152602001609c815250815260200160405180604001604052806044198152602001609c81525081525090506000604051806102a001604052806014815260200160138152602001600d81526020016012815260200160158152602001600e8152602001600c8152602001600f815260200160058152602001600b81526020016006815260200160048152602001600781526020016003815260200160088152602001600281526020016010815260200160018152602001600a81526020016009815260200160118152509050606060006125a2866111eb565b91505060005b60158110156129805760008482601581106125bf57fe5b60200201519050828110156126dc57836126266040518060400160405280600c81526020016b199d5b1b13195859941b1bdd60a21b81525088856015811061260357fe5b60200201515189866015811061261557fe5b60200201516001602002015161318e565b6040516020018083805190602001908083835b602083106126585780518252601f199092019160209182019101612639565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b602083106126a05780518252601f199092019160209182019101612681565b6001836020036101000a0380198251168184511680821785525050505050509050019250505060405160208183030381529060405293506128f9565b828114156128155782600114156127d857836127226040518060400160405280600c81526020016b199d5b1b13195859941b1bdd60a21b81525088856015811061260357fe5b6040516020018083805190602001908083835b602083106127545780518252601f199092019160209182019101612735565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b6020831061279c5780518252601f19909201916020918201910161277d565b6001836020036101000a038019825116818451168082178552505050505050905001925050506040516020818303038152906040529350612810565b836126266040518060400160405280600f81526020016e1c185c9d1a585b13195859941b1bdd608a1b81525088856015811061260357fe5b6128f9565b8361284760405180604001604052806009815260200168195b5c1d1e541b1bdd60ba1b81525088856015811061260357fe5b6040516020018083805190602001908083835b602083106128795780518252601f19909201916020918201910161285a565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b602083106128c15780518252601f1990920191602091820191016128a2565b6001836020036101000a0380198251168184511680821785525050505050509050019250505060405160208183030381529060405293505b81600b141561297757836040516020018082805190602001908083835b602083106129355780518252601f199092019160209182019101612916565b6001836020036101000a03801982511681845116808217855250505050505090500180613e59603e9139603e0191505060405160208183030381529060405293505b506001016125a8565b509095945050505050565b6060612996826103e2565b60405160200180605b614b408239605b0182805190602001908083835b602083106129d25780518252601f1990920191602091820191016129b3565b5181516020939093036101000a6000190180199091169216919091179052661e17ba32bc3a1f60c91b9201918252506040805180830360181901815260079092019052949350505050565b6060612a28826132f0565b612a31836132f0565b60405160200180605c613dfd8239605c01605a61473a8239605a0183805190602001908083835b60208310612a775780518252601f199092019160209182019101612a58565b5181516020939093036101000a60001901801990911692169190911790526e1e17ba39b830b71f1e17ba32bc3a1f60891b920191825250600f01605c613dfd8239605c01605b6148ba8239605b0182805190602001908083835b60208310612af05780518252601f199092019160209182019101612ad1565b5181516020939093036101000a60001901801990911692169190911790526e1e17ba39b830b71f1e17ba32bc3a1f60891b92019182525060408051808303601019018152600f909201905295945050505050565b6060600082600b0b12612b7757620186a082600b0b1315612b6b576106d582600b0b613306565b6106d582600b0b61079d565b620186a082600003600b0b1315612b97576106e882600003600b0b613306565b6106d582600b0b6106c1565b6000808211612bf9576040805162461bcd60e51b815260206004820152601a60248201527f536166654d6174683a206469766973696f6e206279207a65726f000000000000604482015290519081900360640190fd5b818381612c0257fe5b049392505050565b6000828201838110156106b8576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b606083612c708461357d565b612c798461357d565b6040516020018080713c75736520786c696e6b3a687265663d222360701b81525060120184805190602001908083835b60208310612cc85780518252601f199092019160209182019101612ca9565b51815160209384036101000a60001901801990921691161790526411103c1e9160d91b919093019081528551600590910192860191508083835b60208310612d215780518252601f199092019160209182019101612d02565b51815160209384036101000a60001901801990921691161790526411103c9e9160d91b919093019081528451600590910192850191508083835b60208310612d7a5780518252601f199092019160209182019101612d5b565b5181516020939093036101000a60001901801990911692169190911790527911103a3930b739b337b9369e9139b1b0b6329418971a1491179f60311b92019182525060408051808303600519018152601a909201905298975050505050505050565b606084612de88561357d565b612df18561357d565b846040516020018080713c75736520786c696e6b3a687265663d222360701b81525060120185805190602001908083835b60208310612e415780518252601f199092019160209182019101612e22565b51815160209384036101000a60001901801990921691161790526411103c1e9160d91b919093019081528651600590910192870191508083835b60208310612e9a5780518252601f199092019160209182019101612e7b565b51815160209384036101000a60001901801990921691161790526411103c9e9160d91b919093019081528551600590910192860191508083835b60208310612ef35780518252601f199092019160209182019101612ed4565b51815160209384036101000a60001901801990921691161790526711103334b6361e9160c11b919093019081528451600890910192850191508083835b60208310612f4f5780518252601f199092019160209182019101612f30565b5181516020939093036101000a60001901801990911692169190911790527911103a3930b739b337b9369e9139b1b0b6329418971a1491179f60311b92019182525060408051808303600519018152601a90920190529a9950505050505050505050565b6060612fbd613137565b61300a604051806040016040528060078152602001666c656166526f7760c81b815250603b19600e604051806040016040528060078152602001662341384338334160c81b815250612ddc565b6040516020018083805190602001908083835b6020831061303c5780518252601f19909201916020918201910161301d565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b602083106130845780518252601f199092019160209182019101613065565b6001836020036101000a03801982511681845116808217855250505050505090500192505050604051602081830303815290604052905090565b60606130ea604051806040016040528060048152602001631c1b1bdd60e21b8152506022196000612c64565b61300a604051806040016040528060078152602001666c656166526f7760c81b8152506022196000604051806040016040528060078152602001662341384338334160c81b815250612ddc565b60606131416130be565b61300a604051806040016040528060078152602001666c656166526f7760c81b815250602e19600760405180604001604052806007815260200166119c1ca09b192360c91b815250612ddc565b60608361319a8461357d565b6131a38461357d565b6040516020018080713c75736520786c696e6b3a687265663d222360701b81525060120184805190602001908083835b602083106131f25780518252601f1990920191602091820191016131d3565b51815160209384036101000a60001901801990921691161790526411103c1e9160d91b919093019081528551600590910192860191508083835b6020831061324b5780518252601f19909201916020918201910161322c565b51815160209384036101000a60001901801990921691161790526411103c9e9160d91b919093019081528451600590910192850191508083835b602083106132a45780518252601f199092019160209182019101613285565b5181516020939093036101000a6000190180199091169216919091179052631110179f60e11b92019182525060408051808303601b190181526004909201905298975050505050505050565b60606106bb6001600160a01b0383166014610559565b6060620f424082049150620f4240821015613326576106d582600561359d565b6298968082101561333c576106d582600661359d565b6305f5e100821015613353576106d582600761359d565b633b9aca0082101561336a576106d582600861359d565b6402540be400821015613382576106d582600961359d565b64174876e80082101561339a576106d582600a61359d565b64e8d4a510008210156133b2576106d582600b61359d565b6509184e72a0008210156133cb576106d582600c61359d565b655af3107a40008210156133e4576106d582600d61359d565b66038d7ea4c680008210156133fe576106d582600e61359d565b662386f26fc10000821015613418576106d582600f61359d565b67016345785d8a0000821015613433576106d582601061359d565b670de0b6b3a764000082101561344e576106d582601161359d565b678ac7230489e80000821015613469576106d582601261359d565b68056bc75e2d63100000821015613485576106d582601361359d565b683635c9adc5dea000008210156134a1576106d582601461359d565b69021e19e0c9bab24000008210156134be576106d582601561359d565b69152d02c7e14af68000008210156134db576106d582601661359d565b69d3c21bcecceda10000008210156134f8576106d582601761359d565b6a084595161401484a000000821015613516576106d582601861359d565b6a52b7d2dcc80cd2e4000000821015613534576106d582601961359d565b6b033b2e3c9fd0803ce8000000821015613553576106d582601a61359d565b6b204fce5e3e25026110000000821015613572576106d582601b61359d565b6106d582601c61359d565b60606000821215613594576106e88260000361079d565b6106d58261079d565b60606135b061018f84600a85900a612ba3565b6135d261018f620186a06118e76135c88760056136fd565b8890600a0a612ba3565b6135db8461079d565b6040516020018084805190602001908083835b6020831061360d5780518252601f1990920191602091820191016135ee565b6001836020036101000a03801982511681845116808217855250505050505090500180601760f91b81525060010183805190602001908083835b602083106136665780518252601f199092019160209182019101613647565b6001836020036101000a03801982511681845116808217855250505050505090500180606560f81b81525060010182805190602001908083835b602083106136bf5780518252601f1990920191602091820191016136a0565b6001836020036101000a0380198251168184511680821785525050505050509050019350505050604051602081830303815290604052905092915050565b600082821115613754576040805162461bcd60e51b815260206004820152601e60248201527f536166654d6174683a207375627472616374696f6e206f766572666c6f770000604482015290519081900360640190fd5b50900390565b8035600b81900b811461024c57600080fd5b600080600060608486031215613780578283fd5b83356001600160a01b0381168114613796578384fd5b92506137a46020850161375a565b91506137b26040850161375a565b90509250925092565b6000602082840312156137cc578081fd5b5035919050565b600081516137e5818560208601613dcc565b9290920192915050565b7f7d2c207b202274726169745f74797065223a2022696e697469616c207374616c81527f6b2070657220424456222c2022646973706c61795f74797065223a20226e756d60208201526e03132b9111610113b30b63ab2911d1608d1b6040820152604f0190565b607d60f81b815260010190565b7f7d2c207b202274726169745f74797065223a202267726f776e207374616c6b2081527f70657220424456222c2022646973706c61795f74797065223a20226e756d626560208201526c039111610113b30b63ab2911d1609d1b6040820152604d0190565b7f227d2c207b202274726169745f74797065223a20227374656d222c202264697381527f706c61795f74797065223a20226e756d626572222c202276616c7565223a20006020820152603f0190565b7f7d2c207b202274726169745f74797065223a20227374616c6b2067726f776e2081527f706572204244562070657220736561736f6e222c2022646973706c61795f747960208201527703832911d1011373ab6b132b9111610113b30b63ab2911d160451b604082015260580190565b60007f2c202261747472696275746573223a205b207b202274726169745f74797065228252741d10112a37b5b2b7111610113b30b63ab2911d101160591b602083015288516139dd816035850160208d01613dcc565b7f227d2c207b202274726169745f74797065223a2022546f6b656e2041646472656035918401918201526e39b9911610113b30b63ab2911d101160891b60558201528851613a32816064840160208d01613dcc565b7f227d2c207b202274726169745f74797065223a20224964222c202276616c75656064929091019182015263111d101160e11b60848201528751613a7d816088840160208c01613dcc565b613ac7613ac1613abc613ab6613ab1613aab613aa6613aa06088898b01016138c8565b8f6137d3565b6137ef565b8c6137d3565b613863565b896137d3565b613917565b866137d3565b9b9a5050505050505050505050565b607b60f81b81527f226e616d65223a20224265616e7374616c6b2053696c6f204465706f7369747360018201527f222c20226465736372697074696f6e223a2022416e204552433131353520726560218201527f70726573656e74696e6720616e206173736574206465706f736974656420696e60418201527f20746865204265616e7374616c6b2053696c6f2e2053696c6f204465706f736960618201527f7473206761696e207374616c6b20616e64206265616e20736569676e6f72616760818201526203297160ed1b60a18201527f5c6e5c6e444953434c41494d45523a204475652064696c6967656e636520697360a48201527f20696d7065726174697665207768656e20617373657373696e6720746869732060c48201527f4e46542e204f70656e73656120616e64206f74686572204e4654206d61726b6560e48201527f74706c616365732063616368652074686520737667206f757470757420616e646101048201527f20746875732c206d6179207265717569726520746865207573657220746f20726101248201527f65667265736820746865206d6574616461746120746f2070726f7065726c79206101448201527839b437bb903a34329031b7b93932b1ba103b30b63ab2b9971160391b6101648201526000613cd2613ccd613cc761017d8501876137d3565b856137d3565b613856565b949350505050565b60007f646174613a6170706c69636174696f6e2f6a736f6e3b6261736536342c00000082528251613d1281601d850160208701613dcc565b91909101601d0192915050565b6e103eae96101134b6b0b3b2911d101160891b81528151600090613d4a81600f850160208701613dcc565b601160f91b600f939091019283015250601001919050565b6000602082528251806020840152613d81816040850160208701613dcc565b601f01601f19169190910160400192915050565b6020808252601d908201527f53696c6f3a206d6574616461746120646f6573206e6f74206578697374000000604082015260600190565b60005b83811015613de7578181015183820152602001613dcf565b83811115613df6576000848401525b5050505056fe3c7465787420783d223132372220793d223334332220666f6e742d73697a653d223130222066696c6c3d2257686974652220746578742d616e63686f723d226d6964646c652220666f6e742d66616d696c793d22667574757261223e3c75736520786c696e6b3a687265663d222373696c6f2220783d2234372220793d22353522207472616e73666f726d3d227363616c6528312e3729222f3e3c7061746820643d224d35372e34382031392e3438324335372e36343520392e32342034342e3937382e3732372032392e3138372e3436382031332e3339372e32312e34363320382e3330332e3239382031382e3534362e3133342032382e3738382031322e382033372e332032382e3539312033372e35366331352e37392e3235382032382e3732342d372e3833352032382e3838392d31382e3037385a222066696c6c3d2223434343222f3e3c7061746820643d224d37392e35373238203132392e3236354c3132372e343639203135362e3833334c3137352e343433203132392e3234354c3132372e343639203130312e3639374c37392e35373238203132392e3236355a222066696c6c3d2223393434413237222f3e3c7061746820643d224d3137312e383834203131382e39383361342e39333220342e3933322030203020312d312e30313820322e36303620342e37313520342e3731352030203020312d312e38373820312e343339632d2e3436352e3139352d312e3733352e3732372d322e3336342e3137362d2e32343620332e3239382d312e35393320362e3531322d322e32353320372e39353461342e35333220342e3533322030203020312d2e3331332d2e393333632d2e3231312d2e3937352d2e3033382d312e3736332e3037382d322e3239352e3230322d2e3932312e3335332d312e3631322e3436372d322e31342d312e3137372e3639342d322e3634322e3536392d332e3535382d2e3237322d2e3739362d2e3733322d312e3038332d312e3932312d2e3734332d332e3033342e3439382e30313120312e3933392e31303920332e32343720312e31363761352e313320352e313320302030203120312e323120312e343133632e3135392d2e37342e3139392d2e3935382e3233382d312e3137392e3230392d312e3231332e3332322d312e3837322e3237342d322e37323461372e373320372e37332030203020302d2e3930382d332e313737632d2e3737322e3431352d312e3738392e3139362d322e3337382d2e3330342d2e3333392d2e3238372d2e3535362d2e3638322d2e3736342d312e3639326131322e3733392031322e3733392030203020312d2e3137362d332e393039632e3738392e36303320312e343720312e30313920312e39333720312e3238332e3934342e35333620312e3334342e36333920312e37363120312e3136372e3135322e3139332e3634392e3834322e35383620312e3735312d2e3031312e3137322d2e3035332e3739352d2e34363420312e32393361362e383320362e383320302030203120312e33383420322e323237632e31342e3336382e3234322e3734342e33313120312e31352e3130372d2e3230372e3236312d2e3433392e3531312d2e3732322e3435332d2e3531332e38372d2e39393220312e3630342d312e3238342e3638332d2e32373220312e32382d2e32343920312e3732332d2e32333461352e33303220352e33303220302030203120312e3438362e3237335a222f3e3c70617468206f7061636974793d222e34342220643d224d312e38312032362e353332632e3230362e3439342e34383420312e30352e383620312e36336131302e3236362031302e32363620302030203020322e32373820322e3438364c362e3535322037382e32326131372e3237322031372e3237322030203020312d332d372e3431334c312e38312032362e3533325a222066696c6c3d2223453645364536222f3e3c7061746820643d224d2e3436342031392e353434632e3639392031362e35383520312e342033332e31363920322e3039382034392e3735322e30323120322e3338312e343820342e3237382e38383320352e3533392e3237372e38362e37343120322e32373520312e37373820332e3836372e3439342e37353920312e32313220312e3720332e30303220332e33333220312e37333920312e35383620332e333520332e30353620352e37333220342e33393820332e32393320312e38353520362e31353120322e33393620382e37393120322e38393620312e3835352e333520352e3134392e39343820392e3438382e3535366133322e3730372033322e37303720302030203020392e3331352d322e32383763312e3836322d2e37353920342e3634322d312e39313720372e3633332d342e3420312e3334382d312e313220332e3434382d322e38393720352e3139372d352e39356132302e3131342032302e31313420302030203020322e32352d352e393938632e32312d31372e3535322e34322d33352e3130342e3633322d35322e3635376c2d35362e382e393532682e3030315a222066696c6c3d2223423342334233222f3e3c7061746820643d224d3137352e343637203133332e344c3137352e343433203132392e3234354c3132372e343639203135362e3833334c3132372e353037203136302e3930384c3137352e343637203133332e345a222066696c6c3d2223363733333145222f3e3c7061746820643d224d35372e3130382037312e3239632e3138382d31312e3635332d31322e30312d32312e3330332d32372e3234332d32312e3535322d31352e3233342d2e32352d32372e37333620382e3939352d32372e3932332032302e3634392d2e3138372031312e3635342031322e30312032312e3330342032372e3234342032312e3535332031352e3233332e32352032372e3733352d382e3939352032372e3932322d32302e36355a222066696c6c3d2223363636222f3e3c75736520786c696e6b3a687265663d22236c6561662220783d22302220793d2230222f3e3c672069643d227061727469616c4c656166506c6f74223e00000000000000003c7465787420783d223234352220793d2231342e352220666f6e742d73697a653d223132222066696c6c3d2257686974652220746578742d616e63686f723d22656e642220666f6e742d66616d696c793d22667574757261223e5374656d3a203c75736520786c696e6b3a687265663d22236c6561662220783d222d31322220793d222d37222f3e3c747370616e3e3c616e696d617465206174747269627574654e616d653d2278222066726f6d3d223337352220746f3d22353022206475723d223130732220726570656174436f756e743d22696e646566696e69746522202f3e3c7061746820643d224d37392e35333332203133332e3432364c37392e35373237203132392e3236354c3132372e343639203135362e3833334c3132372e353037203136302e3930384c37392e35333332203133332e3432365a222066696c6c3d2223373533393146222f3e3c75736520786c696e6b3a687265663d22236c6561662220783d222d32342220793d222d3134222f3e4142434445464748494a4b4c4d4e4f505152535455565758595a6162636465666768696a6b6c6d6e6f707172737475767778797a303132333435363738392b2f3c7061746820643d226d33332e3039322034392e3434312d362e3338312031352e323131732d362e3037382d31312e31353920362e3338312d31352e32315a222066696c6c3d2223384538453845222f3e3c747370616e3e3c616e696d617465206174747269627574654e616d653d2278222066726f6d3d2235302220746f3d222d32373522206475723d223130732220726570656174436f756e743d22696e646566696e69746522202f3e3c7061746820643d224d362e3431342032382e38396131352e3737372031352e3737372030203020312d322e3039332d322e313436632d2e3835362d312e3036332d322e3435332d332e3039332d322e3937352d362e3131326131312e3736352031312e3736352030203020312d2e3039332d332e3330376c32352e34332d392e393736632e3034332e3134322e3138382e3535352e3630342e3836382e34362e3334362e3934372e333420312e3038362e3333344c362e3431332032382e383838762e3030325a222066696c6c3d2223453645364536222f3e3c7061746820643d226d32362e3732352036342e3835382d2e3039312d2e313735632d2e3032362d2e3034392d322e3633342d342e3932332d2e3836372d392e333720312e3035372d322e37313720332e3531382d342e37323520372e332d352e3934366c2e3138372d2e3036312d362e35332031352e3535325a6d362e3231322d31352e323638632d332e36323120312e3231372d352e39393120332e3136382d372e30323220352e3739382d312e35333820332e3930382e33353520382e3136362e37383820392e3035346c362e3233342d31342e3835325a4d32382e3039332036332e3733376c342e3438342d31302e383773372e33363520362e3333372d342e3438342031302e38375a222066696c6c3d2223384538453845222f3e3c2f673e3c726563742077696474683d2232353522206865696768743d22333530222072783d223130222066696c6c3d223c7465787420783d2231302220793d2231342e352220666f6e742d73697a653d223132222066696c6c3d2257686974652220746578742d616e63686f723d2273746172742220666f6e742d66616d696c793d22667574757261223e5369676e6564536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f773c672069643d227061727469616c4c656166526f77223e0000000000000000003c7265637420783d22302220793d2230222077696474683d2232353522206865696768743d223230222072783d2235222066696c6c3d2223323432343234222f3e3c7265637420783d22302220793d22333330222077696474683d2232353522206865696768743d223230222072783d2235222066696c6c3d2223323432343234222f3e3c70617468206f7061636974793d222e33332220643d224d312e3437372031362e303239632e32352d2e3933312e3730362d322e32353820312e35372d332e3639352e3635352d312e30393220312e3239322d312e38323520312e37362d322e3335382e3538342d2e36363520312e3737362d312e39333420332e3637392d332e323920322e3935332d322e31303520352e3639362d332e303520372e3732332d332e37336133372e33352033372e333520302030203120362e3438352d312e3534376c352e32343220342e33313661312e343820312e34382030203020302d312e3231342e3936374c312e34382031362e3033682d2e3030325a222066696c6c3d2223393939222f3e5369676e6564536166654d6174683a207375627472616374696f6e206f766572666c6f773c75736520786c696e6b3a687265663d222373696c6f2220783d2239392220793d223535222f3e3c672069643d22616c6c506c6f742220636c69702d706174683d2275726c2823626f726465724d61736b29223e3c7061746820643d224d33302e33313420372e313337632e3030392d2e3536312d2e36382d312e3032382d312e3533382d312e3034322d2e3835392d2e3031342d312e3536322e34332d312e3537312e3939312d2e30312e3536322e363820312e30323820312e35333820312e3034322e3835392e30313520312e3536322d2e343320312e35372d2e39395a222066696c6c3d2223363636222f3e3c73766720636c6173733d22737667426f6479222077696474683d2232353522206865696768743d22333530222076696577426f783d2230203020323535203335302220786d6c6e733d22687474703a2f2f7777772e77332e6f72672f323030302f7376672220786d6c6e733a786c696e6b3d22687474703a2f2f7777772e77332e6f72672f313939392f786c696e6b223e3c75736520786c696e6b3a687265663d22236c6561662220783d222d33362220793d222d3231222f3ea264697066735822122071d9f7d6ce9eef834bc9d114c6694d9cf58dbb4e7f6383630d25a7252f5f45de64736f6c63430007060033

Deployed Bytecode

0x608060405234801561001057600080fd5b506004361061004c5760003560e01c806306fdde03146100515780630e89341c1461006f57806395d89b4114610082578063c20b80711461008a575b600080fd5b61005961009d565b6040516100669190613d62565b60405180910390f35b61005961007d3660046137bb565b6100ce565b610059610251565b61005961009836600461376c565b610272565b6040805180820190915260178152764265616e7374616c6b2053696c6f204465706f7369747360481b602082015290565b60606000806100dc8461031e565b9150915060006100eb8361032a565b6001600160a01b038416600090815260396020526040902054909150600160601b900463ffffffff1615801590610128575081600b0b81600b0b12155b61014d5760405162461bcd60e51b815260040161014490613d95565b60405180910390fd5b6000610158846103e2565b61016c856001600160a01b03166014610559565b610177886020610559565b61018386600b0b6106c1565b61019461018f89610761565b61079d565b6101a2888803600b0b61079d565b6101ae61018f8b610878565b6040516020016101c49796959493929190613987565b6040516020818303038152906040529050610226816101e4868686610272565b6040516020016101f49190613d1f565b60408051601f19818403018152908290526102129291602001613ad6565b6040516020818303038152906040526108b4565b6040516020016102369190613cda565b6040516020818303038152906040529450505050505b919050565b60408051808201909152600781526611115413d4d25560ca1b602082015290565b60606102876102828585856109f5565b6108b4565b60405160200180807f646174613a696d6167652f7376672b786d6c3b6261736536342c000000000000815250601a0182805190602001908083835b602083106102e15780518252601f1990920191602091820191016102c2565b6001836020036101000a03801982511681845116808217855250505050505090500191505060405160208183030381529060405290509392505050565b606081901c815b915091565b600080610335610b82565b6001600160a01b038416600090815260398201602052604090205460038201549192506103b29161037d9163ffffffff918216600b0b91600160601b909104811690610b8716565b6001600160a01b038516600090815260398401602052604090205463ffffffff600160201b9091048116600b0b9190610bff16565b6001600160a01b03909316600090815260399091016020526040902054600160801b9004600b0b91909101919050565b60606001600160a01b038216731bea3ccd22f4ebd3d37d731ba31eeca95713716d141561042e5750604080518082019091526008815267075724245414e4c560c41b602082015261024c565b816001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b15801561046757600080fd5b505afa15801561047b573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405260208110156104a457600080fd5b8101908080516040519392919084600160201b8211156104c357600080fd5b9083019060208201858111156104d857600080fd5b8251600160201b8111828201881017156104f157600080fd5b82525081516020918201929091019080838360005b8381101561051e578181015183820152602001610506565b50505050905090810190601f16801561054b5780820380516001836020036101000a031916815260200191505b506040525050509050919050565b606060008260020260020167ffffffffffffffff8111801561057a57600080fd5b506040519080825280601f01601f1916602001820160405280156105a5576020820181803683370190505b509050600360fc1b816000815181106105ba57fe5b60200101906001600160f81b031916908160001a905350600f60fb1b816001815181106105e357fe5b60200101906001600160f81b031916908160001a905350600160028402015b6001811115610664576f181899199a1a9b1b9c1cb0b131b232b360811b85600f166010811061062d57fe5b1a60f81b82828151811061063d57fe5b60200101906001600160f81b031916908160001a90535060049490941c9360001901610602565b5083156106b8576040805162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e74604482015290519081900360640190fd5b90505b92915050565b606060008213156106dc576106d58261079d565b905061024c565b6106e88260000361079d565b6040516020018080602d60f81b81525060010182805190602001908083835b602083106107265780518252601f199092019160209182019101610707565b6001836020036101000a038019825116818451168082178552505050505050905001915050604051602081830303815290604052905061024c565b60008061076c610b82565b6001600160a01b0393909316600090815260399390930160205250506040902054600160401b900463ffffffff1690565b6060816107c257506040805180820190915260018152600360fc1b602082015261024c565b8160005b81156107da57600101600a820491506107c6565b60008167ffffffffffffffff811180156107f357600080fd5b506040519080825280601f01601f19166020018201604052801561081e576020820181803683370190505b50859350905060001982015b831561086f57600a840660300160f81b8282806001900393508151811061084d57fe5b60200101906001600160f81b031916908160001a905350600a8404935061082a565b50949350505050565b600080610883610b82565b6001600160a01b0393909316600090815260399390930160205250506040902054600160201b900463ffffffff1690565b60608151600014156108d5575060408051602081019091526000815261024c565b60006040518060600160405280604081526020016148296040913990506000600384516002018161090257fe5b0460040267ffffffffffffffff8111801561091c57600080fd5b506040519080825280601f01601f191660200182016040528015610947576020820181803683370190505b509050600182016020820185865187015b808210156109b3576003820191508151603f8160121c168501518453600184019350603f81600c1c168501518453600184019350603f8160061c168501518453600184019350603f8116850151845350600183019250610958565b50506003865106600181146109cf57600281146109e2576109ea565b603d6001830353603d60028303536109ea565b603d60018303535b509195945050505050565b6060828203610a0381610ccf565b610a0b610fbf565b610a1483611005565b610a1e8888611094565b604051602001806092614e83823960920185805190602001908083835b60208310610a5a5780518252601f199092019160209182019101610a3b565b51815160209384036101000a600019018019909216911617905287519190930192870191508083835b60208310610aa25780518252601f199092019160209182019101610a83565b51815160209384036101000a600019018019909216911617905286519190930192860191508083835b60208310610aea5780518252601f199092019160209182019101610acb565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b60208310610b325780518252601f199092019160209182019101610b13565b5181516020939093036101000a6000190180199091169216919091179052651e17b9bb339f60d11b92019182525060408051808303601919018152600690920190529a9950505050505050505050565b600090565b6000818303600b83900b8213801590610ba6575083600b0b81600b0b13155b80610bc45750600083600b0b128015610bc4575083600b0b81600b0b135b6106b85760405162461bcd60e51b8152600401808060200182810382526024815260200180614d706024913960400191505060405180910390fd5b600082600b0b60001415610c15575060006106bb565b82600b0b600019148015610c395750600b82900b6b7fffffffffffffffffffffff19145b15610c755760405162461bcd60e51b8152600401808060200182810382526027815260200180614b9b6027913960400191505060405180910390fd5b6000828402905082600b0b84600b0b82600b0b81610c8f57fe5b05600b0b146106b85760405162461bcd60e51b8152600401808060200182810382526027815260200180614b9b6027913960400191505060405180910390fd5b60606000610cdc836111eb565b5090506000610cec82600461123f565b9050610cf66112a1565b610cfe611304565b610d06611622565b610d0f846116e5565b610d18886118b9565b610d2061212a565b610d2861217c565b610d30612213565b6040516020018080651e3232b3399f60d11b81525060060189805190602001908083835b60208310610d735780518252601f199092019160209182019101610d54565b51815160209384036101000a60001901801990921691161790528b5191909301928b0191508083835b60208310610dbb5780518252601f199092019160209182019101610d9c565b51815160209384036101000a60001901801990921691161790528a5191909301928a0191508083835b60208310610e035780518252601f199092019160209182019101610de4565b51815160209384036101000a600019018019909216911617905289519190930192890191508083835b60208310610e4b5780518252601f199092019160209182019101610e2c565b51815160209384036101000a600019018019909216911617905288519190930192880191508083835b60208310610e935780518252601f199092019160209182019101610e74565b51815160209384036101000a600019018019909216911617905287519190930192870191508083835b60208310610edb5780518252601f199092019160209182019101610ebc565b51815160209384036101000a600019018019909216911617905286519190930192860191508083835b60208310610f235780518252601f199092019160209182019101610f04565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b60208310610f6b5780518252601f199092019160209182019101610f4c565b5181516020939093036101000a6000190180199091169216919091179052661e17b232b3399f60c91b92019182525060408051808303601819018152600790920190529d9c50505050505050505050505050565b60606040516020018080614b13602d91396611991a9999991b60c91b602d8201526211179f60e91b60348201526040805160178184030181526037909201905291505090565b606061101082612283565b604051602001806054614d94823960540182805190602001908083835b6020831061104c5780518252601f19909201916020918201910161102d565b5181516020939093036101000a6000190180199091169216919091179052631e17b39f60e11b92019182525060408051808303601b1901815260049092019052949350505050565b606061109f8361298b565b6110a884612a1d565b6110b184612b44565b604051602001806041614be2823960410184805190602001908083835b602083106110ed5780518252601f1990920191602091820191016110ce565b6001836020036101000a03801982511681845116808217855250505050505090500180614c236043913960430183805190602001908083835b602083106111455780518252601f199092019160209182019101611126565b6001836020036101000a038019825116818451168082178552505050505050905001806146b26060913960600182805190602001908083835b6020831061119d5780518252601f19909201916020918201910161117e565b5181516020939093036101000a6000190180199091169216919091179052661e17ba32bc3a1f60c91b9201918252506040805180830360181901815260079092019052979650505050505050565b600080611200600b84900b630bebc200612ba3565b91506112186001611212846010612ba3565b90612c0a565b9050600061122783601061123f565b111561032557611238816001612c0a565b9050915091565b6000808211611290576040805162461bcd60e51b8152602060048201526018602482015277536166654d6174683a206d6f64756c6f206279207a65726f60401b604482015290519081900360640190fd5b81838161129957fe5b069392505050565b6040516c1e339034b21e91383637ba111f60991b60208201908152606091602d01606c613f458239606c0180614794606c9139606c0160686145478239631e17b39f60e11b606882015260408051604c818403018152606c909201905291505090565b6060611330604051806040016040528060048152602001631c1b1bdd60e21b8152506022196000612c64565b61137d604051806040016040528060078152602001666c656166526f7760c81b8152506022196000604051806040016040528060078152602001662341384338334160c81b815250612ddc565b6113ca604051806040016040528060078152602001666c656166526f7760c81b815250602e19600760405180604001604052806007815260200166119c1ca09b192360c91b815250612ddc565b611417604051806040016040528060078152602001666c656166526f7760c81b815250603b19600e604051806040016040528060078152602001662341384338334160c81b815250612ddc565b611464604051806040016040528060078152602001666c656166526f7760c81b815250604819601560405180604001604052806007815260200166119c1ca09b192360c91b815250612ddc565b6040516020018080741e339034b21e91333ab6362632b0b3283637ba111f60591b81525060150186805190602001908083835b602083106114b65780518252601f199092019160209182019101611497565b51815160209384036101000a600019018019909216911617905288519190930192880191508083835b602083106114fe5780518252601f1990920191602091820191016114df565b51815160209384036101000a600019018019909216911617905287519190930192870191508083835b602083106115465780518252601f199092019160209182019101611527565b51815160209384036101000a600019018019909216911617905286519190930192860191508083835b6020831061158e5780518252601f19909201916020918201910161156f565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b602083106115d65780518252601f1990920191602091820191016115b7565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b81525060040195505050505050604051602081830303815290604052905090565b606061164e604051806040016040528060048152602001631c1b1bdd60e21b8152506022196000612c64565b6040516020018080711e339034b21e9132b6b83a3ca83637ba111f60711b81525060120182805190602001908083835b6020831061169d5780518252601f19909201916020918201910161167e565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b815250600401915050604051602081830303815290604052905090565b606081611729575060408051600080516020614bc28339815191526020820152631e17b39f60e11b60378201528151601b818303018152603b90910190915261024c565b816001141561178057604051600080516020614bc28339815191526020820190815290603701602561466d823960250180631e17b39f60e11b8152506004019050604051602081830303815290604052905061024c565b81600214156117e157604051600080516020614bc28339815191526020820190815290603701602561466d82396025016028614712823960280180631e17b39f60e11b8152506004019050604051602081830303815290604052905061024c565b816003141561184c57604051600080516020614bc28339815191526020820190815290603701602561466d8239602501602861471282396028016029614800823960290180631e17b39f60e11b8152506004019050604051602081830303815290604052905061024c565b604051600080516020614bc28339815191526020820190815290603701602561466d8239602501602861471282396028016029614800823960290180614f156029913960290180631e17b39f60e11b8152506004019050604051602081830303815290604052905061024c565b606060006118d46010611212600b86900b630bebc200612ba3565b905060006118ed60046118e78482612ba3565b9061123f565b905060006118fc83600461123f565b905081611b8e578015611a6257611933604051806040016040528060048152602001631c1b1bdd60e21b8152506022196000612c64565b6119876040518060400160405280600e81526020016d7061727469616c4c656166526f7760901b8152506022196000604051806040016040528060078152602001662341384338334160c81b815250612ddc565b604051602001808060008051602061469283398151915281525060180183805190602001908083835b602083106119cf5780518252601f1990920191602091820191016119b0565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b60208310611a175780518252601f1990920191602091820191016119f8565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b815250600401925050506040516020818303038152906040529350611b8e565b611a6a612fb3565b611ab7604051806040016040528060078152602001666c656166526f7760c81b815250604819601560405180604001604052806007815260200166119c1ca09b192360c91b815250612ddc565b604051602001808060008051602061469283398151915281525060180183805190602001908083835b60208310611aff5780518252601f199092019160209182019101611ae0565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b60208310611b475780518252601f199092019160209182019101611b28565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b8152506004019250505060405160208183030381529060405293505b8160011415611d6a578015611cd457611ba56130be565b611bf96040518060400160405280600e81526020016d7061727469616c4c656166526f7760901b815250602e19600760405180604001604052806007815260200166119c1ca09b192360c91b815250612ddc565b604051602001808060008051602061469283398151915281525060180183805190602001908083835b60208310611c415780518252601f199092019160209182019101611c22565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b60208310611c895780518252601f199092019160209182019101611c6a565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b815250600401925050506040516020818303038152906040529350611d6a565b611cdc6130be565b604051602001808060008051602061469283398151915281525060180182805190602001908083835b60208310611d245780518252601f199092019160209182019101611d05565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b81525060040191505060405160208183030381529060405293505b8160021415611f46578015611eb057611d81613137565b611dd56040518060400160405280600e81526020016d7061727469616c4c656166526f7760901b815250603b19600e604051806040016040528060078152602001662341384338334160c81b815250612ddc565b604051602001808060008051602061469283398151915281525060180183805190602001908083835b60208310611e1d5780518252601f199092019160209182019101611dfe565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b60208310611e655780518252601f199092019160209182019101611e46565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b815250600401925050506040516020818303038152906040529350611f46565b611eb8613137565b604051602001808060008051602061469283398151915281525060180182805190602001908083835b60208310611f005780518252601f199092019160209182019101611ee1565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b81525060040191505060405160208183030381529060405293505b816003141561212257801561208c57611f5d612fb3565b611fb16040518060400160405280600e81526020016d7061727469616c4c656166526f7760901b815250604819601560405180604001604052806007815260200166119c1ca09b192360c91b815250612ddc565b604051602001808060008051602061469283398151915281525060180183805190602001908083835b60208310611ff95780518252601f199092019160209182019101611fda565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b602083106120415780518252601f199092019160209182019101612022565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b815250600401925050506040516020818303038152906040529350612122565b612094612fb3565b604051602001808060008051602061469283398151915281525060180182805190602001908083835b602083106120dc5780518252601f1990920191602091820191016120bd565b6001836020036101000a03801982511681845116808217855250505050505090500180631e17b39f60e11b81525060040191505060405160208183030381529060405293505b505050919050565b6040516c1e339034b21e913632b0b3111f60991b60208201908152606091602d01610339613fb18239631e17b39f60e11b6103398201526040805161031d81840301815261033d909201905291505090565b6040516c1e339034b21e9139b4b637911f60991b60208201908152606091602d0160be6145af823960be016101b961438e82396101b90160ae613e97823960ae01609b614de88239609b0160da614915823960da0161010a614c66823961010a0160a46142ea823960a401605161486982396051016101246149ef8239610124019050604051602081830303815290604052905090565b6040516f1e339034b21e913632b0b32937bb911f60811b60208201908152606091603001602561466d8239602501602861471282396028016029614800823960290180614f1560299139631e17b39f60e11b602982015260408051600d818403018152602d909201905291505090565b60606000604051806102a001604052806040518060400160405280604419815260200160a319815250815260200160405180604001604052806045815260200160a3198152508152602001604051806040016040528060008152602001607b1981525081526020016040518060400160405280608a8152602001607b19815250815260200160405180604001604052806089198152602001607b198152508152602001604051806040016040528060441981526020016053198152508152602001604051806040016040528060458152602001605319815250815260200160405180604001604052806089198152602001602b198152508152602001604051806040016040528060008152602001602b1981525081526020016040518060400160405280608a8152602001602b198152508152602001604051806040016040528060441981526020016003198152508152602001604051806040016040528060458152602001600319815250815260200160405180604001604052806089198152602001602481525081526020016040518060400160405280608a81526020016024815250815260200160405180604001604052806044198152602001604c8152508152602001604051806040016040528060458152602001604c81525081526020016040518060400160405280608919815260200160748152508152602001604051806040016040528060008152602001607481525081526020016040518060400160405280608a815260200160748152508152602001604051806040016040528060458152602001609c815250815260200160405180604001604052806044198152602001609c81525081525090506000604051806102a001604052806014815260200160138152602001600d81526020016012815260200160158152602001600e8152602001600c8152602001600f815260200160058152602001600b81526020016006815260200160048152602001600781526020016003815260200160088152602001600281526020016010815260200160018152602001600a81526020016009815260200160118152509050606060006125a2866111eb565b91505060005b60158110156129805760008482601581106125bf57fe5b60200201519050828110156126dc57836126266040518060400160405280600c81526020016b199d5b1b13195859941b1bdd60a21b81525088856015811061260357fe5b60200201515189866015811061261557fe5b60200201516001602002015161318e565b6040516020018083805190602001908083835b602083106126585780518252601f199092019160209182019101612639565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b602083106126a05780518252601f199092019160209182019101612681565b6001836020036101000a0380198251168184511680821785525050505050509050019250505060405160208183030381529060405293506128f9565b828114156128155782600114156127d857836127226040518060400160405280600c81526020016b199d5b1b13195859941b1bdd60a21b81525088856015811061260357fe5b6040516020018083805190602001908083835b602083106127545780518252601f199092019160209182019101612735565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b6020831061279c5780518252601f19909201916020918201910161277d565b6001836020036101000a038019825116818451168082178552505050505050905001925050506040516020818303038152906040529350612810565b836126266040518060400160405280600f81526020016e1c185c9d1a585b13195859941b1bdd608a1b81525088856015811061260357fe5b6128f9565b8361284760405180604001604052806009815260200168195b5c1d1e541b1bdd60ba1b81525088856015811061260357fe5b6040516020018083805190602001908083835b602083106128795780518252601f19909201916020918201910161285a565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b602083106128c15780518252601f1990920191602091820191016128a2565b6001836020036101000a0380198251168184511680821785525050505050509050019250505060405160208183030381529060405293505b81600b141561297757836040516020018082805190602001908083835b602083106129355780518252601f199092019160209182019101612916565b6001836020036101000a03801982511681845116808217855250505050505090500180613e59603e9139603e0191505060405160208183030381529060405293505b506001016125a8565b509095945050505050565b6060612996826103e2565b60405160200180605b614b408239605b0182805190602001908083835b602083106129d25780518252601f1990920191602091820191016129b3565b5181516020939093036101000a6000190180199091169216919091179052661e17ba32bc3a1f60c91b9201918252506040805180830360181901815260079092019052949350505050565b6060612a28826132f0565b612a31836132f0565b60405160200180605c613dfd8239605c01605a61473a8239605a0183805190602001908083835b60208310612a775780518252601f199092019160209182019101612a58565b5181516020939093036101000a60001901801990911692169190911790526e1e17ba39b830b71f1e17ba32bc3a1f60891b920191825250600f01605c613dfd8239605c01605b6148ba8239605b0182805190602001908083835b60208310612af05780518252601f199092019160209182019101612ad1565b5181516020939093036101000a60001901801990911692169190911790526e1e17ba39b830b71f1e17ba32bc3a1f60891b92019182525060408051808303601019018152600f909201905295945050505050565b6060600082600b0b12612b7757620186a082600b0b1315612b6b576106d582600b0b613306565b6106d582600b0b61079d565b620186a082600003600b0b1315612b97576106e882600003600b0b613306565b6106d582600b0b6106c1565b6000808211612bf9576040805162461bcd60e51b815260206004820152601a60248201527f536166654d6174683a206469766973696f6e206279207a65726f000000000000604482015290519081900360640190fd5b818381612c0257fe5b049392505050565b6000828201838110156106b8576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b606083612c708461357d565b612c798461357d565b6040516020018080713c75736520786c696e6b3a687265663d222360701b81525060120184805190602001908083835b60208310612cc85780518252601f199092019160209182019101612ca9565b51815160209384036101000a60001901801990921691161790526411103c1e9160d91b919093019081528551600590910192860191508083835b60208310612d215780518252601f199092019160209182019101612d02565b51815160209384036101000a60001901801990921691161790526411103c9e9160d91b919093019081528451600590910192850191508083835b60208310612d7a5780518252601f199092019160209182019101612d5b565b5181516020939093036101000a60001901801990911692169190911790527911103a3930b739b337b9369e9139b1b0b6329418971a1491179f60311b92019182525060408051808303600519018152601a909201905298975050505050505050565b606084612de88561357d565b612df18561357d565b846040516020018080713c75736520786c696e6b3a687265663d222360701b81525060120185805190602001908083835b60208310612e415780518252601f199092019160209182019101612e22565b51815160209384036101000a60001901801990921691161790526411103c1e9160d91b919093019081528651600590910192870191508083835b60208310612e9a5780518252601f199092019160209182019101612e7b565b51815160209384036101000a60001901801990921691161790526411103c9e9160d91b919093019081528551600590910192860191508083835b60208310612ef35780518252601f199092019160209182019101612ed4565b51815160209384036101000a60001901801990921691161790526711103334b6361e9160c11b919093019081528451600890910192850191508083835b60208310612f4f5780518252601f199092019160209182019101612f30565b5181516020939093036101000a60001901801990911692169190911790527911103a3930b739b337b9369e9139b1b0b6329418971a1491179f60311b92019182525060408051808303600519018152601a90920190529a9950505050505050505050565b6060612fbd613137565b61300a604051806040016040528060078152602001666c656166526f7760c81b815250603b19600e604051806040016040528060078152602001662341384338334160c81b815250612ddc565b6040516020018083805190602001908083835b6020831061303c5780518252601f19909201916020918201910161301d565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b602083106130845780518252601f199092019160209182019101613065565b6001836020036101000a03801982511681845116808217855250505050505090500192505050604051602081830303815290604052905090565b60606130ea604051806040016040528060048152602001631c1b1bdd60e21b8152506022196000612c64565b61300a604051806040016040528060078152602001666c656166526f7760c81b8152506022196000604051806040016040528060078152602001662341384338334160c81b815250612ddc565b60606131416130be565b61300a604051806040016040528060078152602001666c656166526f7760c81b815250602e19600760405180604001604052806007815260200166119c1ca09b192360c91b815250612ddc565b60608361319a8461357d565b6131a38461357d565b6040516020018080713c75736520786c696e6b3a687265663d222360701b81525060120184805190602001908083835b602083106131f25780518252601f1990920191602091820191016131d3565b51815160209384036101000a60001901801990921691161790526411103c1e9160d91b919093019081528551600590910192860191508083835b6020831061324b5780518252601f19909201916020918201910161322c565b51815160209384036101000a60001901801990921691161790526411103c9e9160d91b919093019081528451600590910192850191508083835b602083106132a45780518252601f199092019160209182019101613285565b5181516020939093036101000a6000190180199091169216919091179052631110179f60e11b92019182525060408051808303601b190181526004909201905298975050505050505050565b60606106bb6001600160a01b0383166014610559565b6060620f424082049150620f4240821015613326576106d582600561359d565b6298968082101561333c576106d582600661359d565b6305f5e100821015613353576106d582600761359d565b633b9aca0082101561336a576106d582600861359d565b6402540be400821015613382576106d582600961359d565b64174876e80082101561339a576106d582600a61359d565b64e8d4a510008210156133b2576106d582600b61359d565b6509184e72a0008210156133cb576106d582600c61359d565b655af3107a40008210156133e4576106d582600d61359d565b66038d7ea4c680008210156133fe576106d582600e61359d565b662386f26fc10000821015613418576106d582600f61359d565b67016345785d8a0000821015613433576106d582601061359d565b670de0b6b3a764000082101561344e576106d582601161359d565b678ac7230489e80000821015613469576106d582601261359d565b68056bc75e2d63100000821015613485576106d582601361359d565b683635c9adc5dea000008210156134a1576106d582601461359d565b69021e19e0c9bab24000008210156134be576106d582601561359d565b69152d02c7e14af68000008210156134db576106d582601661359d565b69d3c21bcecceda10000008210156134f8576106d582601761359d565b6a084595161401484a000000821015613516576106d582601861359d565b6a52b7d2dcc80cd2e4000000821015613534576106d582601961359d565b6b033b2e3c9fd0803ce8000000821015613553576106d582601a61359d565b6b204fce5e3e25026110000000821015613572576106d582601b61359d565b6106d582601c61359d565b60606000821215613594576106e88260000361079d565b6106d58261079d565b60606135b061018f84600a85900a612ba3565b6135d261018f620186a06118e76135c88760056136fd565b8890600a0a612ba3565b6135db8461079d565b6040516020018084805190602001908083835b6020831061360d5780518252601f1990920191602091820191016135ee565b6001836020036101000a03801982511681845116808217855250505050505090500180601760f91b81525060010183805190602001908083835b602083106136665780518252601f199092019160209182019101613647565b6001836020036101000a03801982511681845116808217855250505050505090500180606560f81b81525060010182805190602001908083835b602083106136bf5780518252601f1990920191602091820191016136a0565b6001836020036101000a0380198251168184511680821785525050505050509050019350505050604051602081830303815290604052905092915050565b600082821115613754576040805162461bcd60e51b815260206004820152601e60248201527f536166654d6174683a207375627472616374696f6e206f766572666c6f770000604482015290519081900360640190fd5b50900390565b8035600b81900b811461024c57600080fd5b600080600060608486031215613780578283fd5b83356001600160a01b0381168114613796578384fd5b92506137a46020850161375a565b91506137b26040850161375a565b90509250925092565b6000602082840312156137cc578081fd5b5035919050565b600081516137e5818560208601613dcc565b9290920192915050565b7f7d2c207b202274726169745f74797065223a2022696e697469616c207374616c81527f6b2070657220424456222c2022646973706c61795f74797065223a20226e756d60208201526e03132b9111610113b30b63ab2911d1608d1b6040820152604f0190565b607d60f81b815260010190565b7f7d2c207b202274726169745f74797065223a202267726f776e207374616c6b2081527f70657220424456222c2022646973706c61795f74797065223a20226e756d626560208201526c039111610113b30b63ab2911d1609d1b6040820152604d0190565b7f227d2c207b202274726169745f74797065223a20227374656d222c202264697381527f706c61795f74797065223a20226e756d626572222c202276616c7565223a20006020820152603f0190565b7f7d2c207b202274726169745f74797065223a20227374616c6b2067726f776e2081527f706572204244562070657220736561736f6e222c2022646973706c61795f747960208201527703832911d1011373ab6b132b9111610113b30b63ab2911d160451b604082015260580190565b60007f2c202261747472696275746573223a205b207b202274726169745f74797065228252741d10112a37b5b2b7111610113b30b63ab2911d101160591b602083015288516139dd816035850160208d01613dcc565b7f227d2c207b202274726169745f74797065223a2022546f6b656e2041646472656035918401918201526e39b9911610113b30b63ab2911d101160891b60558201528851613a32816064840160208d01613dcc565b7f227d2c207b202274726169745f74797065223a20224964222c202276616c75656064929091019182015263111d101160e11b60848201528751613a7d816088840160208c01613dcc565b613ac7613ac1613abc613ab6613ab1613aab613aa6613aa06088898b01016138c8565b8f6137d3565b6137ef565b8c6137d3565b613863565b896137d3565b613917565b866137d3565b9b9a5050505050505050505050565b607b60f81b81527f226e616d65223a20224265616e7374616c6b2053696c6f204465706f7369747360018201527f222c20226465736372697074696f6e223a2022416e204552433131353520726560218201527f70726573656e74696e6720616e206173736574206465706f736974656420696e60418201527f20746865204265616e7374616c6b2053696c6f2e2053696c6f204465706f736960618201527f7473206761696e207374616c6b20616e64206265616e20736569676e6f72616760818201526203297160ed1b60a18201527f5c6e5c6e444953434c41494d45523a204475652064696c6967656e636520697360a48201527f20696d7065726174697665207768656e20617373657373696e6720746869732060c48201527f4e46542e204f70656e73656120616e64206f74686572204e4654206d61726b6560e48201527f74706c616365732063616368652074686520737667206f757470757420616e646101048201527f20746875732c206d6179207265717569726520746865207573657220746f20726101248201527f65667265736820746865206d6574616461746120746f2070726f7065726c79206101448201527839b437bb903a34329031b7b93932b1ba103b30b63ab2b9971160391b6101648201526000613cd2613ccd613cc761017d8501876137d3565b856137d3565b613856565b949350505050565b60007f646174613a6170706c69636174696f6e2f6a736f6e3b6261736536342c00000082528251613d1281601d850160208701613dcc565b91909101601d0192915050565b6e103eae96101134b6b0b3b2911d101160891b81528151600090613d4a81600f850160208701613dcc565b601160f91b600f939091019283015250601001919050565b6000602082528251806020840152613d81816040850160208701613dcc565b601f01601f19169190910160400192915050565b6020808252601d908201527f53696c6f3a206d6574616461746120646f6573206e6f74206578697374000000604082015260600190565b60005b83811015613de7578181015183820152602001613dcf565b83811115613df6576000848401525b5050505056fe3c7465787420783d223132372220793d223334332220666f6e742d73697a653d223130222066696c6c3d2257686974652220746578742d616e63686f723d226d6964646c652220666f6e742d66616d696c793d22667574757261223e3c75736520786c696e6b3a687265663d222373696c6f2220783d2234372220793d22353522207472616e73666f726d3d227363616c6528312e3729222f3e3c7061746820643d224d35372e34382031392e3438324335372e36343520392e32342034342e3937382e3732372032392e3138372e3436382031332e3339372e32312e34363320382e3330332e3239382031382e3534362e3133342032382e3738382031322e382033372e332032382e3539312033372e35366331352e37392e3235382032382e3732342d372e3833352032382e3838392d31382e3037385a222066696c6c3d2223434343222f3e3c7061746820643d224d37392e35373238203132392e3236354c3132372e343639203135362e3833334c3137352e343433203132392e3234354c3132372e343639203130312e3639374c37392e35373238203132392e3236355a222066696c6c3d2223393434413237222f3e3c7061746820643d224d3137312e383834203131382e39383361342e39333220342e3933322030203020312d312e30313820322e36303620342e37313520342e3731352030203020312d312e38373820312e343339632d2e3436352e3139352d312e3733352e3732372d322e3336342e3137362d2e32343620332e3239382d312e35393320362e3531322d322e32353320372e39353461342e35333220342e3533322030203020312d2e3331332d2e393333632d2e3231312d2e3937352d2e3033382d312e3736332e3037382d322e3239352e3230322d2e3932312e3335332d312e3631322e3436372d322e31342d312e3137372e3639342d322e3634322e3536392d332e3535382d2e3237322d2e3739362d2e3733322d312e3038332d312e3932312d2e3734332d332e3033342e3439382e30313120312e3933392e31303920332e32343720312e31363761352e313320352e313320302030203120312e323120312e343133632e3135392d2e37342e3139392d2e3935382e3233382d312e3137392e3230392d312e3231332e3332322d312e3837322e3237342d322e37323461372e373320372e37332030203020302d2e3930382d332e313737632d2e3737322e3431352d312e3738392e3139362d322e3337382d2e3330342d2e3333392d2e3238372d2e3535362d2e3638322d2e3736342d312e3639326131322e3733392031322e3733392030203020312d2e3137362d332e393039632e3738392e36303320312e343720312e30313920312e39333720312e3238332e3934342e35333620312e3334342e36333920312e37363120312e3136372e3135322e3139332e3634392e3834322e35383620312e3735312d2e3031312e3137322d2e3035332e3739352d2e34363420312e32393361362e383320362e383320302030203120312e33383420322e323237632e31342e3336382e3234322e3734342e33313120312e31352e3130372d2e3230372e3236312d2e3433392e3531312d2e3732322e3435332d2e3531332e38372d2e39393220312e3630342d312e3238342e3638332d2e32373220312e32382d2e32343920312e3732332d2e32333461352e33303220352e33303220302030203120312e3438362e3237335a222f3e3c70617468206f7061636974793d222e34342220643d224d312e38312032362e353332632e3230362e3439342e34383420312e30352e383620312e36336131302e3236362031302e32363620302030203020322e32373820322e3438364c362e3535322037382e32326131372e3237322031372e3237322030203020312d332d372e3431334c312e38312032362e3533325a222066696c6c3d2223453645364536222f3e3c7061746820643d224d2e3436342031392e353434632e3639392031362e35383520312e342033332e31363920322e3039382034392e3735322e30323120322e3338312e343820342e3237382e38383320352e3533392e3237372e38362e37343120322e32373520312e37373820332e3836372e3439342e37353920312e32313220312e3720332e30303220332e33333220312e37333920312e35383620332e333520332e30353620352e37333220342e33393820332e32393320312e38353520362e31353120322e33393620382e37393120322e38393620312e3835352e333520352e3134392e39343820392e3438382e3535366133322e3730372033322e37303720302030203020392e3331352d322e32383763312e3836322d2e37353920342e3634322d312e39313720372e3633332d342e3420312e3334382d312e313220332e3434382d322e38393720352e3139372d352e39356132302e3131342032302e31313420302030203020322e32352d352e393938632e32312d31372e3535322e34322d33352e3130342e3633322d35322e3635376c2d35362e382e393532682e3030315a222066696c6c3d2223423342334233222f3e3c7061746820643d224d3137352e343637203133332e344c3137352e343433203132392e3234354c3132372e343639203135362e3833334c3132372e353037203136302e3930384c3137352e343637203133332e345a222066696c6c3d2223363733333145222f3e3c7061746820643d224d35372e3130382037312e3239632e3138382d31312e3635332d31322e30312d32312e3330332d32372e3234332d32312e3535322d31352e3233342d2e32352d32372e37333620382e3939352d32372e3932332032302e3634392d2e3138372031312e3635342031322e30312032312e3330342032372e3234342032312e3535332031352e3233332e32352032372e3733352d382e3939352032372e3932322d32302e36355a222066696c6c3d2223363636222f3e3c75736520786c696e6b3a687265663d22236c6561662220783d22302220793d2230222f3e3c672069643d227061727469616c4c656166506c6f74223e00000000000000003c7465787420783d223234352220793d2231342e352220666f6e742d73697a653d223132222066696c6c3d2257686974652220746578742d616e63686f723d22656e642220666f6e742d66616d696c793d22667574757261223e5374656d3a203c75736520786c696e6b3a687265663d22236c6561662220783d222d31322220793d222d37222f3e3c747370616e3e3c616e696d617465206174747269627574654e616d653d2278222066726f6d3d223337352220746f3d22353022206475723d223130732220726570656174436f756e743d22696e646566696e69746522202f3e3c7061746820643d224d37392e35333332203133332e3432364c37392e35373237203132392e3236354c3132372e343639203135362e3833334c3132372e353037203136302e3930384c37392e35333332203133332e3432365a222066696c6c3d2223373533393146222f3e3c75736520786c696e6b3a687265663d22236c6561662220783d222d32342220793d222d3134222f3e4142434445464748494a4b4c4d4e4f505152535455565758595a6162636465666768696a6b6c6d6e6f707172737475767778797a303132333435363738392b2f3c7061746820643d226d33332e3039322034392e3434312d362e3338312031352e323131732d362e3037382d31312e31353920362e3338312d31352e32315a222066696c6c3d2223384538453845222f3e3c747370616e3e3c616e696d617465206174747269627574654e616d653d2278222066726f6d3d2235302220746f3d222d32373522206475723d223130732220726570656174436f756e743d22696e646566696e69746522202f3e3c7061746820643d224d362e3431342032382e38396131352e3737372031352e3737372030203020312d322e3039332d322e313436632d2e3835362d312e3036332d322e3435332d332e3039332d322e3937352d362e3131326131312e3736352031312e3736352030203020312d2e3039332d332e3330376c32352e34332d392e393736632e3034332e3134322e3138382e3535352e3630342e3836382e34362e3334362e3934372e333420312e3038362e3333344c362e3431332032382e383838762e3030325a222066696c6c3d2223453645364536222f3e3c7061746820643d226d32362e3732352036342e3835382d2e3039312d2e313735632d2e3032362d2e3034392d322e3633342d342e3932332d2e3836372d392e333720312e3035372d322e37313720332e3531382d342e37323520372e332d352e3934366c2e3138372d2e3036312d362e35332031352e3535325a6d362e3231322d31352e323638632d332e36323120312e3231372d352e39393120332e3136382d372e30323220352e3739382d312e35333820332e3930382e33353520382e3136362e37383820392e3035346c362e3233342d31342e3835325a4d32382e3039332036332e3733376c342e3438342d31302e383773372e33363520362e3333372d342e3438342031302e38375a222066696c6c3d2223384538453845222f3e3c2f673e3c726563742077696474683d2232353522206865696768743d22333530222072783d223130222066696c6c3d223c7465787420783d2231302220793d2231342e352220666f6e742d73697a653d223132222066696c6c3d2257686974652220746578742d616e63686f723d2273746172742220666f6e742d66616d696c793d22667574757261223e5369676e6564536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f773c672069643d227061727469616c4c656166526f77223e0000000000000000003c7265637420783d22302220793d2230222077696474683d2232353522206865696768743d223230222072783d2235222066696c6c3d2223323432343234222f3e3c7265637420783d22302220793d22333330222077696474683d2232353522206865696768743d223230222072783d2235222066696c6c3d2223323432343234222f3e3c70617468206f7061636974793d222e33332220643d224d312e3437372031362e303239632e32352d2e3933312e3730362d322e32353820312e35372d332e3639352e3635352d312e30393220312e3239322d312e38323520312e37362d322e3335382e3538342d2e36363520312e3737362d312e39333420332e3637392d332e323920322e3935332d322e31303520352e3639362d332e303520372e3732332d332e37336133372e33352033372e333520302030203120362e3438352d312e3534376c352e32343220342e33313661312e343820312e34382030203020302d312e3231342e3936374c312e34382031362e3033682d2e3030325a222066696c6c3d2223393939222f3e5369676e6564536166654d6174683a207375627472616374696f6e206f766572666c6f773c75736520786c696e6b3a687265663d222373696c6f2220783d2239392220793d223535222f3e3c672069643d22616c6c506c6f742220636c69702d706174683d2275726c2823626f726465724d61736b29223e3c7061746820643d224d33302e33313420372e313337632e3030392d2e3536312d2e36382d312e3032382d312e3533382d312e3034322d2e3835392d2e3031342d312e3536322e34332d312e3537312e3939312d2e30312e3536322e363820312e30323820312e35333820312e3034322e3835392e30313520312e3536322d2e343320312e35372d2e39395a222066696c6c3d2223363636222f3e3c73766720636c6173733d22737667426f6479222077696474683d2232353522206865696768743d22333530222076696577426f783d2230203020323535203335302220786d6c6e733d22687474703a2f2f7777772e77332e6f72672f323030302f7376672220786d6c6e733a786c696e6b3d22687474703a2f2f7777772e77332e6f72672f313939392f786c696e6b223e3c75736520786c696e6b3a687265663d22236c6561662220783d222d33362220793d222d3231222f3ea264697066735822122071d9f7d6ce9eef834bc9d114c6694d9cf58dbb4e7f6383630d25a7252f5f45de64736f6c63430007060033

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.