ETH Price: $1,600.02 (+0.74%)
 

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

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
ConvertFacet

Compiler Version
v0.7.6+commit.7338295f

Optimization Enabled:
Yes with 1000 runs

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

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import {C} from "contracts/C.sol";
import {LibSilo} from "contracts/libraries/Silo/LibSilo.sol";
import {LibTokenSilo} from "contracts/libraries/Silo/LibTokenSilo.sol";
import {LibSafeMath32} from "contracts/libraries/LibSafeMath32.sol";
import {LibConvert} from "contracts/libraries/Convert/LibConvert.sol";
import {ReentrancyGuard} from "../ReentrancyGuard.sol";
import {LibBytes} from "contracts/libraries/LibBytes.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/**
 * @author Publius
 * @title ConvertFacet handles converting Deposited assets within the Silo.
 **/
contract ConvertFacet is ReentrancyGuard {
    using SafeMath for uint256;
    using SafeCast for uint256;
    using LibSafeMath32 for uint32;

    event Convert(
        address indexed account,
        address fromToken,
        address toToken,
        uint256 fromAmount,
        uint256 toAmount
    );

    event RemoveDeposit(
        address indexed account,
        address indexed token,
        int96 stem,
        uint256 amount,
        uint256 bdv
    );

    event RemoveDeposits(
        address indexed account,
        address indexed token,
        int96[] stems,
        uint256[] amounts,
        uint256 amount,
        uint256[] bdvs
    );

    /**
     * @notice convert allows a user to convert a deposit to another deposit,
     * given that the conversion is supported by the ConvertFacet.
     * For example, a user can convert LP into Bean, only when beanstalk is below peg, 
     * or convert beans into LP, only when beanstalk is above peg.
     * @param convertData  input parameters to determine the conversion type.
     * @param stems the stems of the deposits to convert 
     * @param amounts the amounts within each deposit to convert
     * @return toStem the new stems of the converted deposit
     * @return fromAmount the amount of tokens converted from
     * @return toAmount the amount of tokens converted to
     * @return fromBdv the bdv of the deposits converted from
     * @return toBdv the bdv of the deposit converted to
     */
    function convert(
        bytes calldata convertData,
        int96[] memory stems,
        uint256[] memory amounts
    )
        external
        payable
        nonReentrant
        returns (int96 toStem, uint256 fromAmount, uint256 toAmount, uint256 fromBdv, uint256 toBdv)
    {
        address toToken; address fromToken; uint256 grownStalk;
        (toToken, fromToken, toAmount, fromAmount) = LibConvert.convert(
            convertData
        );

        LibSilo._mow(msg.sender, fromToken);
        LibSilo._mow(msg.sender, toToken);

        (grownStalk, fromBdv) = _withdrawTokens(
            fromToken,
            stems,
            amounts,
            fromAmount
        );

        uint256 newBdv = LibTokenSilo.beanDenominatedValue(toToken, toAmount);
        toBdv = newBdv > fromBdv ? newBdv : fromBdv;

        toStem = _depositTokensForConvert(toToken, toAmount, toBdv, grownStalk);

        emit Convert(msg.sender, fromToken, toToken, fromAmount, toAmount);
    }

    function _withdrawTokens(
        address token,
        int96[] memory stems,
        uint256[] memory amounts,
        uint256 maxTokens
    ) internal returns (uint256, uint256) {
        require(
            stems.length == amounts.length,
            "Convert: stems, amounts are diff lengths."
        );
        LibSilo.AssetsRemoved memory a;
        uint256 depositBDV;
        uint256 i = 0;
        // a bracket is included here to avoid the "stack too deep" error.
        {
            uint256[] memory bdvsRemoved = new uint256[](stems.length);
            uint256[] memory depositIds = new uint256[](stems.length);
            while ((i < stems.length) && (a.tokensRemoved < maxTokens)) {
                if (a.tokensRemoved.add(amounts[i]) < maxTokens) {
                    //keeping track of stalk removed must happen before we actually remove the deposit
                    //this is because LibTokenSilo.grownStalkForDeposit() uses the current deposit info
                    depositBDV = LibTokenSilo.removeDepositFromAccount(
                        msg.sender,
                        token,
                        stems[i],
                        amounts[i]
                    );
                    bdvsRemoved[i] = depositBDV;
                    a.stalkRemoved = a.stalkRemoved.add(
                        LibSilo.stalkReward(
                            stems[i],
                            LibTokenSilo.stemTipForToken(token),
                            depositBDV.toUint128()
                        )
                    );
                    
                } else {
                    amounts[i] = maxTokens.sub(a.tokensRemoved);
                    
                    depositBDV = LibTokenSilo.removeDepositFromAccount(
                        msg.sender,
                        token,
                        stems[i],
                        amounts[i]
                    );

                    bdvsRemoved[i] = depositBDV;
                    a.stalkRemoved = a.stalkRemoved.add(
                        LibSilo.stalkReward(
                            stems[i],
                        LibTokenSilo.stemTipForToken(token),
                            depositBDV.toUint128()
                        )
                    );
                    
                }
                
                a.tokensRemoved = a.tokensRemoved.add(amounts[i]);
                a.bdvRemoved = a.bdvRemoved.add(depositBDV);
                
                depositIds[i] = uint256(LibBytes.packAddressAndStem(
                    token,
                    stems[i]
                ));
                i++;
            }
            for (i; i < stems.length; ++i) amounts[i] = 0;
            
            emit RemoveDeposits(
                msg.sender,
                token,
                stems,
                amounts,
                a.tokensRemoved,
                bdvsRemoved
            );

            emit LibSilo.TransferBatch(
                msg.sender, 
                msg.sender,
                address(0), 
                depositIds, 
                amounts
            );
        }

        require(
            a.tokensRemoved == maxTokens,
            "Convert: Not enough tokens removed."
        );
        LibTokenSilo.decrementTotalDeposited(token, a.tokensRemoved, a.bdvRemoved);
        LibSilo.burnStalk(
            msg.sender,
            a.stalkRemoved.add(a.bdvRemoved.mul(s.ss[token].stalkIssuedPerBdv))
        );
        return (a.stalkRemoved, a.bdvRemoved);
    }

    //this is only used internal to the convert facet
    function _depositTokensForConvert(
        address token,
        uint256 amount,
        uint256 bdv,
        uint256 grownStalk // stalk grown previously by this deposit
    ) internal returns (int96 stem) {
        require(bdv > 0 && amount > 0, "Convert: BDV or amount is 0.");

        //calculate stem index we need to deposit at from grownStalk and bdv
        //if we attempt to deposit at a half-season (a grown stalk index that would fall between seasons)
        //then in affect we lose that partial season's worth of stalk when we deposit
        //so here we need to update grownStalk to be the amount you'd have with the above deposit
        
        /// @dev the two functions were combined into one function to save gas.
        // _stemTip = LibTokenSilo.grownStalkAndBdvToStem(IERC20(token), grownStalk, bdv);
        // grownStalk = uint256(LibTokenSilo.calculateStalkFromStemAndBdv(IERC20(token), _stemTip, bdv));

        (grownStalk, stem) = LibTokenSilo.calculateGrownStalkAndStem(token, grownStalk, bdv);

        LibSilo.mintStalk(msg.sender, bdv.mul(LibTokenSilo.stalkIssuedPerBdv(token)).add(grownStalk));

        LibTokenSilo.incrementTotalDeposited(token, amount, bdv);
        LibTokenSilo.addDepositToAccount(
            msg.sender, 
            token, 
            stem, 
            amount, 
            bdv,
            LibTokenSilo.Transfer.emitTransferSingle
        );
    }
}

File 2 of 54 : 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 54 : 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 4 of 54 : 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 5 of 54 : 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 6 of 54 : IUniswapV3Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';

/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
    IUniswapV3PoolImmutables,
    IUniswapV3PoolState,
    IUniswapV3PoolDerivedState,
    IUniswapV3PoolActions,
    IUniswapV3PoolOwnerActions,
    IUniswapV3PoolEvents
{

}

File 7 of 54 : IUniswapV3PoolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;

    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
    /// on tickLower, tickUpper, the amount of liquidity, and the current price.
    /// @param recipient The address for which the liquidity will be created
    /// @param tickLower The lower tick of the position in which to add liquidity
    /// @param tickUpper The upper tick of the position in which to add liquidity
    /// @param amount The amount of liquidity to mint
    /// @param data Any data that should be passed through to the callback
    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
    function mint(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Collects tokens owed to a position
    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
    /// @param recipient The address which should receive the fees collected
    /// @param tickLower The lower tick of the position for which to collect fees
    /// @param tickUpper The upper tick of the position for which to collect fees
    /// @param amount0Requested How much token0 should be withdrawn from the fees owed
    /// @param amount1Requested How much token1 should be withdrawn from the fees owed
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
    /// @dev Fees must be collected separately via a call to #collect
    /// @param tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
    /// with 0 amount{0,1} and sending the donation amount(s) from the callback
    /// @param recipient The address which will receive the token0 and token1 amounts
    /// @param amount0 The amount of token0 to send
    /// @param amount1 The amount of token1 to send
    /// @param data Any data to be passed through to the callback
    function flash(
        address recipient,
        uint256 amount0,
        uint256 amount1,
        bytes calldata data
    ) external;

    /// @notice Increase the maximum number of price and liquidity observations that this pool will store
    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
    /// the input observationCardinalityNext.
    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}

File 8 of 54 : IUniswapV3PoolDerivedState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
    /// you must call it with secondsAgos = [3600, 0].
    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
    /// timestamp
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
    /// snapshot is taken and the second snapshot is taken.
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
        external
        view
        returns (
            int56 tickCumulativeInside,
            uint160 secondsPerLiquidityInsideX128,
            uint32 secondsInside
        );
}

File 9 of 54 : IUniswapV3PoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
    event Initialize(uint160 sqrtPriceX96, int24 tick);

    /// @notice Emitted when liquidity is minted for a given position
    /// @param sender The address that minted the liquidity
    /// @param owner The owner of the position and recipient of any minted liquidity
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity minted to the position range
    /// @param amount0 How much token0 was required for the minted liquidity
    /// @param amount1 How much token1 was required for the minted liquidity
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted when fees are collected by the owner of a position
    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
    /// @param owner The owner of the position for which fees are collected
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount0 The amount of token0 fees collected
    /// @param amount1 The amount of token1 fees collected
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );

    /// @notice Emitted when a position's liquidity is removed
    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
    /// @param owner The owner of the position for which liquidity is removed
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity to remove
    /// @param amount0 The amount of token0 withdrawn
    /// @param amount1 The amount of token1 withdrawn
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted by the pool for any swaps between token0 and token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the output of the swap
    /// @param amount0 The delta of the token0 balance of the pool
    /// @param amount1 The delta of the token1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of price of the pool after the swap
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick
    );

    /// @notice Emitted by the pool for any flashes of token0/token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the tokens from flash
    /// @param amount0 The amount of token0 that was flashed
    /// @param amount1 The amount of token1 that was flashed
    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );

    /// @notice Emitted by the pool for increases to the number of observations that can be stored
    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
    /// just before a mint/swap/burn.
    /// @param observationCardinalityNextOld The previous value of the next observation cardinality
    /// @param observationCardinalityNextNew The updated value of the next observation cardinality
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld,
        uint16 observationCardinalityNextNew
    );

    /// @notice Emitted when the protocol fee is changed by the pool
    /// @param feeProtocol0Old The previous value of the token0 protocol fee
    /// @param feeProtocol1Old The previous value of the token1 protocol fee
    /// @param feeProtocol0New The updated value of the token0 protocol fee
    /// @param feeProtocol1New The updated value of the token1 protocol fee
    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);

    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
    /// @param sender The address that collects the protocol fees
    /// @param recipient The address that receives the collected protocol fees
    /// @param amount0 The amount of token0 protocol fees that is withdrawn
    /// @param amount0 The amount of token1 protocol fees that is withdrawn
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}

File 10 of 54 : IUniswapV3PoolImmutables.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token1() external view returns (address);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The pool tick spacing
    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
    /// This value is an int24 to avoid casting even though it is always positive.
    /// @return The tick spacing
    function tickSpacing() external view returns (int24);

    /// @notice The maximum amount of position liquidity that can use any tick in the range
    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
    /// @return The max amount of liquidity per tick
    function maxLiquidityPerTick() external view returns (uint128);
}

File 11 of 54 : IUniswapV3PoolOwnerActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    /// @param feeProtocol0 new protocol fee for token0 of the pool
    /// @param feeProtocol1 new protocol fee for token1 of the pool
    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;

    /// @notice Collect the protocol fee accrued to the pool
    /// @param recipient The address to which collected protocol fees should be sent
    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
    /// @return amount0 The protocol fee collected in token0
    /// @return amount1 The protocol fee collected in token1
    function collectProtocol(
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);
}

File 12 of 54 : IUniswapV3PoolState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
    /// when accessed externally.
    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
    /// tick The current tick of the pool, i.e. according to the last tick transition that was run.
    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
    /// boundary.
    /// observationIndex The index of the last oracle observation that was written,
    /// observationCardinality The current maximum number of observations stored in the pool,
    /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
    /// feeProtocol The protocol fee for both tokens of the pool.
    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
    /// unlocked Whether the pool is currently locked to reentrancy
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal0X128() external view returns (uint256);

    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal1X128() external view returns (uint256);

    /// @notice The amounts of token0 and token1 that are owed to the protocol
    /// @dev Protocol fees will never exceed uint128 max in either token
    function protocolFees() external view returns (uint128 token0, uint128 token1);

    /// @notice The currently in range liquidity available to the pool
    /// @dev This value has no relationship to the total liquidity across all ticks
    function liquidity() external view returns (uint128);

    /// @notice Look up information about a specific tick in the pool
    /// @param tick The tick to look up
    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
    /// tick upper,
    /// liquidityNet how much liquidity changes when the pool price crosses the tick,
    /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
    /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
    /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
    /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
    /// secondsOutside the seconds spent on the other side of the tick from the current tick,
    /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
    /// a specific position.
    function ticks(int24 tick)
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
    function tickBitmap(int16 wordPosition) external view returns (uint256);

    /// @notice Returns the information about a position by the position's key
    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
    /// @return _liquidity The amount of liquidity in the position,
    /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
    /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
    /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
    /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
    function positions(bytes32 key)
        external
        view
        returns (
            uint128 _liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    /// @notice Returns data about a specific observation index
    /// @param index The element of the observations array to fetch
    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
    /// ago, rather than at a specific index in the array.
    /// @return blockTimestamp The timestamp of the observation,
    /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
    /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
    /// Returns initialized whether the observation has been initialized and the values are safe to use
    function observations(uint256 index)
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );
}

File 13 of 54 : FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0 <0.8.0;

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        // 512-bit multiply [prod1 prod0] = a * b
        // Compute the product mod 2**256 and mod 2**256 - 1
        // then use the Chinese Remainder Theorem to reconstruct
        // the 512 bit result. The result is stored in two 256
        // variables such that product = prod1 * 2**256 + prod0
        uint256 prod0; // Least significant 256 bits of the product
        uint256 prod1; // Most significant 256 bits of the product
        assembly {
            let mm := mulmod(a, b, not(0))
            prod0 := mul(a, b)
            prod1 := sub(sub(mm, prod0), lt(mm, prod0))
        }

        // Handle non-overflow cases, 256 by 256 division
        if (prod1 == 0) {
            require(denominator > 0);
            assembly {
                result := div(prod0, denominator)
            }
            return result;
        }

        // Make sure the result is less than 2**256.
        // Also prevents denominator == 0
        require(denominator > prod1);

        ///////////////////////////////////////////////
        // 512 by 256 division.
        ///////////////////////////////////////////////

        // Make division exact by subtracting the remainder from [prod1 prod0]
        // Compute remainder using mulmod
        uint256 remainder;
        assembly {
            remainder := mulmod(a, b, denominator)
        }
        // Subtract 256 bit number from 512 bit number
        assembly {
            prod1 := sub(prod1, gt(remainder, prod0))
            prod0 := sub(prod0, remainder)
        }

        // Factor powers of two out of denominator
        // Compute largest power of two divisor of denominator.
        // Always >= 1.
        uint256 twos = -denominator & denominator;
        // Divide denominator by power of two
        assembly {
            denominator := div(denominator, twos)
        }

        // Divide [prod1 prod0] by the factors of two
        assembly {
            prod0 := div(prod0, twos)
        }
        // Shift in bits from prod1 into prod0. For this we need
        // to flip `twos` such that it is 2**256 / twos.
        // If twos is zero, then it becomes one
        assembly {
            twos := add(div(sub(0, twos), twos), 1)
        }
        prod0 |= prod1 * twos;

        // Invert denominator mod 2**256
        // Now that denominator is an odd number, it has an inverse
        // modulo 2**256 such that denominator * inv = 1 mod 2**256.
        // Compute the inverse by starting with a seed that is correct
        // correct for four bits. That is, denominator * inv = 1 mod 2**4
        uint256 inv = (3 * denominator) ^ 2;
        // Now use Newton-Raphson iteration to improve the precision.
        // Thanks to Hensel's lifting lemma, this also works in modular
        // arithmetic, doubling the correct bits in each step.
        inv *= 2 - denominator * inv; // inverse mod 2**8
        inv *= 2 - denominator * inv; // inverse mod 2**16
        inv *= 2 - denominator * inv; // inverse mod 2**32
        inv *= 2 - denominator * inv; // inverse mod 2**64
        inv *= 2 - denominator * inv; // inverse mod 2**128
        inv *= 2 - denominator * inv; // inverse mod 2**256

        // Because the division is now exact we can divide by multiplying
        // with the modular inverse of denominator. This will give us the
        // correct result modulo 2**256. Since the precoditions guarantee
        // that the outcome is less than 2**256, this is the final result.
        // We don't need to compute the high bits of the result and prod1
        // is no longer required.
        result = prod0 * inv;
        return result;
    }

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        result = mulDiv(a, b, denominator);
        if (mulmod(a, b, denominator) > 0) {
            require(result < type(uint256).max);
            result++;
        }
    }
}

File 14 of 54 : TickMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.8.0;

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
    int24 internal constant MAX_TICK = -MIN_TICK;

    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_RATIO = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
    /// at the given tick
    function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
        require(absTick <= uint256(MAX_TICK), 'T');

        uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
        if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
        if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
        if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
        if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
        if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
        if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
        if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
        if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
        if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
        if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
        if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
        if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
        if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
        if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
        if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
        if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
        if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
        if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
        if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;

        if (tick > 0) ratio = type(uint256).max / ratio;

        // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
        // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
        // we round up in the division so getTickAtSqrtRatio of the output price is always consistent
        sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
    }

    /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
    function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
        // second inequality must be < because the price can never reach the price at the max tick
        require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
        uint256 ratio = uint256(sqrtPriceX96) << 32;

        uint256 r = ratio;
        uint256 msb = 0;

        assembly {
            let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(5, gt(r, 0xFFFFFFFF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(4, gt(r, 0xFFFF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(3, gt(r, 0xFF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(2, gt(r, 0xF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(1, gt(r, 0x3))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := gt(r, 0x1)
            msb := or(msb, f)
        }

        if (msb >= 128) r = ratio >> (msb - 127);
        else r = ratio << (127 - msb);

        int256 log_2 = (int256(msb) - 128) << 64;

        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(63, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(62, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(61, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(60, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(59, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(58, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(57, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(56, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(55, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(54, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(53, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(52, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(51, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(50, f))
        }

        int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number

        int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
        int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);

        tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
    }
}

File 15 of 54 : OracleLibrary.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.8.0;

import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';

/// @title Oracle library
/// @notice Provides functions to integrate with V3 pool oracle
library OracleLibrary {
    /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool
    /// @param pool Address of the pool that we want to observe
    /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means
    /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp
    /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp
    function consult(address pool, uint32 secondsAgo)
        internal
        view
        returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)
    {
        require(secondsAgo != 0, 'BP');

        uint32[] memory secondsAgos = new uint32[](2);
        secondsAgos[0] = secondsAgo;
        secondsAgos[1] = 0;

        (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =
            IUniswapV3Pool(pool).observe(secondsAgos);

        int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
        uint160 secondsPerLiquidityCumulativesDelta =
            secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];

        arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgo);
        // Always round to negative infinity
        if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgo != 0)) arithmeticMeanTick--;

        // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128
        uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;
        harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));
    }

    /// @notice Given a tick and a token amount, calculates the amount of token received in exchange
    /// @param tick Tick value used to calculate the quote
    /// @param baseAmount Amount of token to be converted
    /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
    /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
    /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
    function getQuoteAtTick(
        int24 tick,
        uint128 baseAmount,
        address baseToken,
        address quoteToken
    ) internal pure returns (uint256 quoteAmount) {
        uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);

        // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
        if (sqrtRatioX96 <= type(uint128).max) {
            uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
            quoteAmount = baseToken < quoteToken
                ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
                : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
        } else {
            uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
            quoteAmount = baseToken < quoteToken
                ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
                : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
        }
    }

    /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation
    /// @param pool Address of Uniswap V3 pool that we want to observe
    /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool
    function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {
        (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();
        require(observationCardinality > 0, 'NI');

        (uint32 observationTimestamp, , , bool initialized) =
            IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality);

        // The next index might not be initialized if the cardinality is in the process of increasing
        // In this case the oldest observation is always in index 0
        if (!initialized) {
            (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);
        }

        secondsAgo = uint32(block.timestamp) - observationTimestamp;
    }

    /// @notice Given a pool, it returns the tick value as of the start of the current block
    /// @param pool Address of Uniswap V3 pool
    /// @return The tick that the pool was in at the start of the current block
    function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) {
        (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();

        // 2 observations are needed to reliably calculate the block starting tick
        require(observationCardinality > 1, 'NEO');

        // If the latest observation occurred in the past, then no tick-changing trades have happened in this block
        // therefore the tick in `slot0` is the same as at the beginning of the current block.
        // We don't need to check if this observation is initialized - it is guaranteed to be.
        (uint32 observationTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, ) =
            IUniswapV3Pool(pool).observations(observationIndex);
        if (observationTimestamp != uint32(block.timestamp)) {
            return (tick, IUniswapV3Pool(pool).liquidity());
        }

        uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;
        (
            uint32 prevObservationTimestamp,
            int56 prevTickCumulative,
            uint160 prevSecondsPerLiquidityCumulativeX128,
            bool prevInitialized
        ) = IUniswapV3Pool(pool).observations(prevIndex);

        require(prevInitialized, 'ONI');

        uint32 delta = observationTimestamp - prevObservationTimestamp;
        tick = int24((tickCumulative - prevTickCumulative) / delta);
        uint128 liquidity =
            uint128(
                (uint192(delta) * type(uint160).max) /
                    (uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32)
            );
        return (tick, liquidity);
    }

    /// @notice Information for calculating a weighted arithmetic mean tick
    struct WeightedTickData {
        int24 tick;
        uint128 weight;
    }

    /// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick
    /// @param weightedTickData An array of ticks and weights
    /// @return weightedArithmeticMeanTick The weighted arithmetic mean tick
    /// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not,
    /// extreme care must be taken to ensure that ticks are comparable (including decimal differences).
    /// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price.
    function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData)
        internal
        pure
        returns (int24 weightedArithmeticMeanTick)
    {
        // Accumulates the sum of products between each tick and its weight
        int256 numerator;

        // Accumulates the sum of the weights
        uint256 denominator;

        // Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic
        for (uint256 i; i < weightedTickData.length; i++) {
            numerator += weightedTickData[i].tick * int256(weightedTickData[i].weight);
            denominator += weightedTickData[i].weight;
        }

        weightedArithmeticMeanTick = int24(numerator / int256(denominator));
        // Always round to negative infinity
        if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--;
    }

    /// @notice Returns the "synthetic" tick which represents the price of the first entry in `tokens` in terms of the last
    /// @dev Useful for calculating relative prices along routes.
    /// @dev There must be one tick for each pairwise set of tokens.
    /// @param tokens The token contract addresses
    /// @param ticks The ticks, representing the price of each token pair in `tokens`
    /// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens`
    function getChainedPrice(address[] memory tokens, int24[] memory ticks)
        internal
        pure
        returns (int256 syntheticTick)
    {
        require(tokens.length - 1 == ticks.length, 'DL');
        for (uint256 i = 1; i <= ticks.length; i++) {
            // check the tokens for address sort order, then accumulate the
            // ticks into the running synthetic tick, ensuring that intermediate tokens "cancel out"
            tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1];
        }
    }
}

File 16 of 54 : 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 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_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 deposits A Farmer's Silo Deposits stored as a map from Token address to Season of Deposit to Deposit.
     * @param withdrawals 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
     */
    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].legacyDeposits` 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 deltaRoots; // the number of roots to add, in the case where a farmer has mowed in the morning
        SeasonOfPlenty deprecated; // DEPRECATED – Replant reset the Season of Plenty mechanism
        uint256 roots; // A Farmer's Root balance.
        uint256 wrappedBeans; // DEPRECATED – Replant generalized Internal Balances. Wrapped Beans are now stored at the AppStorage level.
        mapping(address => mapping(uint32 => Deposit)) legacyDeposits; // 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; // DEPRECATED - Zero withdraw eliminates a need for withdraw mapping
        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) deposits; // 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, and a hash for an ERC721/1155 deposit.
        mapping(address => MowStatus) mowStatuses; // Store a MowStatus for each Whitelisted Silo token
        mapping(address => bool) isApprovedForAll; // ERC1155 isApprovedForAll mapping 
    }
}

/**
 * @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.stepWeather}.
     * @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 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 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/32)
        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.
     * @param seeds The Seeds Per BDV that the Silo mints in exchange for Depositing this Token.
     * @param stalk The Stalk Per BDV that the Silo mints in exchange for Depositing this Token.
     * @dev A Token is considered Whitelisted if there exists a non-zero {SiloSettings} selector.
     * 
     * Note: `selector` is an encoded function selector that pertains to an 
     * external view function with the following signature:
     * 
     * `function tokenToBdv(uint256 amount) public view returns (uint256);`
     * 
     * It is called by {LibTokenSilo} through the use of delegate call to calculate 
     * the BDV of Tokens at the time of Deposit.
     */
    struct SiloSettings {
        /*
         * @dev: 
         * 
         * `selector` is an encoded function selector that pertains to 
         * an external view Beanstalk function with the following signature:
         * 
         * ```
         * function tokenToBdv(uint256 amount) public view returns (uint256);
         * ```
         * 
         * It is called by `LibTokenSilo` through the use of `delegatecall`
         * to calculate a token's BDV at the time of Deposit.
         */
        bytes4 selector;
        /*
         * @dev The Stalk Per BDV Per Season 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.
         */
        uint32 stalkEarnedPerSeason;
        /*
         * @dev The Stalk Per BDV that the Silo grants in exchange for Depositing this Token.
         * previously just called stalk.
         */
        uint32 stalkIssuedPerBdv;
        /*
         * @dev The last season in which the stalkEarnedPerSeason for this token was updated
         */
		uint32 milestoneSeason;
        /*
         * @dev The cumulative amount of grown stalk per BDV for this Silo depositable token at the last stalkEarnedPerSeason update
         */
		int96 milestoneStem;

        /*
         @dev 1 byte of space is used for different encoding types.
         */
        bytes1 encodeType;

        /// @dev  7 bytes of additional storage space is available here.

    }

    /**
     * @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;
    }
}

/**
 * @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 cases The 24 Weather cases (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 depreciated through various updates. Storage slots can be left alone or reused.
 * @param 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 vestingPeriodRoots the number of roots to add to the global roots, in the case the user plants in the morning. // placed here to save a storage slot.s
 * @param recapitalized The nubmer 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 beanEthPrice Stores the beanEthPrice during the sunrise() function. Returns 1 otherwise.
 * @param migratedBdvs Stores the total migrated BDV since the implementation of the migrated BDV counter. See {LibLegacyTokenSilo.incrementMigratedBdv} for more info.
 */
struct AppStorage {
    uint8 deprecated_index;
    int8[32] 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 newEarnedStalk; // ──────┐ 16
    uint128 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 beanEthPrice;

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

File 17 of 54 : ReentrancyGuard.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./AppStorage.sol";

/**
 * @author Beanstalk Farms
 * @title Variation of Oepn Zeppelins reentrant guard to include Silo Update
 * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts%2Fsecurity%2FReentrancyGuard.sol
**/
abstract contract ReentrancyGuard {
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    AppStorage internal s;
    
    modifier nonReentrant() {
        require(s.reentrantStatus != _ENTERED, "ReentrancyGuard: reentrant call");
        s.reentrantStatus = _ENTERED;
        _;
        s.reentrantStatus = _NOT_ENTERED;
    }
}

File 18 of 54 : 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 UNIV3_ETH_USDC_POOL = 0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640; // 0.05% pool
    address internal constant UNIV3_ETH_USDT_POOL = 0x11b815efB8f581194ae79006d24E0d814B7697F6; // 0.05% pool

    // 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 BEANSTALK_PUMP = 0xBA510f10E3095B83a0F33aa9ad2544E22570a87C;
    address internal constant BEAN_ETH_WELL = 0xBEA0e11282e2bB5893bEcE110cF199501e872bAd;

    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 UniV3EthUsdc() internal pure returns (address){
        return UNIV3_ETH_USDC_POOL;
    }

    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 19 of 54 : IBeanstalkWellFunction.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import {IWellFunction} from "./IWellFunction.sol";

/**
 * @title IBeanstalkWellFunction
 * @notice Defines all necessary functions for Beanstalk to support a Well Function in addition to functions defined in the primary interface.
 * This includes 2 functions to solve for a given reserve value suc that the average price between
 * the given reserve and all other reserves equals the average of the input ratios.
 * `calcReserveAtRatioSwap` assumes the target ratios are reached through executing a swap.
 * `calcReserveAtRatioLiquidity` assumes the target ratios are reached through adding/removing liquidity.
 */
interface IBeanstalkWellFunction is IWellFunction {
    /**
     * @notice Calculates the `j` reserve such that `π_{i | i != j} (d reserves_j / d reserves_i) = π_{i | i != j}(ratios_j / ratios_i)`.
     * assumes that reserve_j is being swapped for other reserves in the Well.
     * @dev used by Beanstalk to calculate the deltaB every Season
     * @param reserves The reserves of the Well
     * @param j The index of the reserve to solve for
     * @param ratios The ratios of reserves to solve for
     * @param data Well function data provided on every call
     * @return reserve The resulting reserve at the jth index
     */
    function calcReserveAtRatioSwap(
        uint[] calldata reserves,
        uint j,
        uint[] calldata ratios,
        bytes calldata data
    ) external view returns (uint reserve);

    /**
     * @notice Calculates the `j` reserve such that `π_{i | i != j} (d reserves_j / d reserves_i) = π_{i | i != j}(ratios_j / ratios_i)`.
     * assumes that reserve_j is being added or removed in exchange for LP Tokens.
     * @dev used by Beanstalk to calculate the max deltaB that can be converted in/out of a Well.
     * @param reserves The reserves of the Well
     * @param j The index of the reserve to solve for
     * @param ratios The ratios of reserves to solve for
     * @param data Well function data provided on every call
     * @return reserve The resulting reserve at the jth index
     */
    function calcReserveAtRatioLiquidity(
        uint[] calldata reserves,
        uint j,
        uint[] calldata ratios,
        bytes calldata data
    ) external pure returns (uint reserve);
}

File 20 of 54 : IWell.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

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

/**
 * @title Call is the struct that contains the target address and extra calldata of a generic call.
 */
struct Call {
    address target; // The address the call is executed on.
    bytes data; // Extra calldata to be passed during the call
}

/**
 * @title IWell is the interface for the Well contract.
 *
 * In order for a Well to be verified using a permissionless on-chain registry, a Well Implementation should:
 * - Not be able to self-destruct (Aquifer's registry would be vulnerable to a metamorphic contract attack)
 * - Not be able to change its tokens, Well Function, Pumps and Well Data
 */
interface IWell {
    /**
     * @notice Emitted when a Swap occurs.
     * @param fromToken The token swapped from
     * @param toToken The token swapped to
     * @param amountIn The amount of `fromToken` transferred into the Well
     * @param amountOut The amount of `toToken` transferred out of the Well
     * @param recipient The address that received `toToken`
     */
    event Swap(IERC20 fromToken, IERC20 toToken, uint256 amountIn, uint256 amountOut, address recipient);

    /**
     * @notice Emitted when liquidity is added to the Well.
     * @param tokenAmountsIn The amount of each token added to the Well
     * @param lpAmountOut The amount of LP tokens minted
     * @param recipient The address that received the LP tokens
     */
    event AddLiquidity(uint256[] tokenAmountsIn, uint256 lpAmountOut, address recipient);

    /**
     * @notice Emitted when liquidity is removed from the Well as multiple underlying tokens.
     * @param lpAmountIn The amount of LP tokens burned
     * @param tokenAmountsOut The amount of each underlying token removed
     * @param recipient The address that received the underlying tokens
     * @dev Gas cost scales with `n` tokens.
     */
    event RemoveLiquidity(uint256 lpAmountIn, uint256[] tokenAmountsOut, address recipient);

    /**
     * @notice Emitted when liquidity is removed from the Well as a single underlying token.
     * @param lpAmountIn The amount of LP tokens burned
     * @param tokenOut The underlying token removed
     * @param tokenAmountOut The amount of `tokenOut` removed
     * @param recipient The address that received the underlying tokens
     * @dev Emitting a separate event when removing liquidity as a single token
     * saves gas, since `tokenAmountsOut` in {RemoveLiquidity} must emit a value
     * for each token in the Well.
     */
    event RemoveLiquidityOneToken(uint256 lpAmountIn, IERC20 tokenOut, uint256 tokenAmountOut, address recipient);

    /**
     * @notice Emitted when a Shift occurs.
     * @param reserves The ending reserves after a shift
     * @param toToken The token swapped to
     * @param amountOut The amount of `toToken` transferred out of the Well
     * @param recipient The address that received `toToken`
     */
    event Shift(uint256[] reserves, IERC20 toToken, uint256 amountOut, address recipient);

    /**
     * @notice Emitted when a Sync occurs.
     * @param reserves The ending reserves after a sync
     * @param lpAmountOut The amount of LP tokens received from the sync.
     * @param recipient The address that received the LP tokens
     */
    event Sync(uint256[] reserves, uint256 lpAmountOut, address recipient);

    //////////////////// WELL DEFINITION ////////////////////

    /**
     * @notice Returns a list of ERC20 tokens supported by the Well.
     */
    function tokens() external view returns (IERC20[] memory);

    /**
     * @notice Returns the Well function as a Call struct.
     * @dev Contains the address of the Well function contract and extra data to
     * pass during calls.
     *
     * **Well functions** define a relationship between the reserves of the
     * tokens in the Well and the number of LP tokens.
     *
     * A Well function MUST implement {IWellFunction}.
     */
    function wellFunction() external view returns (Call memory);

    /**
     * @notice Returns the Pumps attached to the Well as Call structs.
     * @dev Contains the addresses of the Pumps contract and extra data to pass
     * during calls.
     *
     * **Pumps** are on-chain oracles that are updated every time the Well is
     * interacted with.
     *
     * A Pump is not required for Well operation. For Wells without a Pump:
     * `pumps().length = 0`.
     *
     * An attached Pump MUST implement {IPump}.
     */
    function pumps() external view returns (Call[] memory);

    /**
     * @notice Returns the Well data that the Well was bored with.
     * @dev The existence and signature of Well data is determined by each individual implementation.
     */
    function wellData() external view returns (bytes memory);

    /**
     * @notice Returns the Aquifer that created this Well.
     * @dev Wells can be permissionlessly bored in an Aquifer.
     *
     * Aquifers stores the implementation that was used to bore the Well.
     */
    function aquifer() external view returns (address);

    /**
     * @notice Returns the tokens, Well Function, Pumps and Well Data associated
     * with the Well as well as the Aquifer that deployed the Well.
     */
    function well()
        external
        view
        returns (
            IERC20[] memory _tokens,
            Call memory _wellFunction,
            Call[] memory _pumps,
            bytes memory _wellData,
            address _aquifer
        );

    //////////////////// SWAP: FROM ////////////////////

    /**
     * @notice Swaps from an exact amount of `fromToken` to a minimum amount of `toToken`.
     * @param fromToken The token to swap from
     * @param toToken The token to swap to
     * @param amountIn The amount of `fromToken` to spend
     * @param minAmountOut The minimum amount of `toToken` to receive
     * @param recipient The address to receive `toToken`
     * @param deadline The timestamp after which this operation is invalid
     * @return amountOut The amount of `toToken` received
     */
    function swapFrom(
        IERC20 fromToken,
        IERC20 toToken,
        uint256 amountIn,
        uint256 minAmountOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256 amountOut);

    /**
     * @notice Swaps from an exact amount of `fromToken` to a minimum amount of `toToken` and supports fee on transfer tokens.
     * @param fromToken The token to swap from
     * @param toToken The token to swap to
     * @param amountIn The amount of `fromToken` to spend
     * @param minAmountOut The minimum amount of `toToken` to take from the Well. Note that if `toToken` charges a fee on transfer, `recipient` will receive less than this amount.
     * @param recipient The address to receive `toToken`
     * @param deadline The timestamp after which this operation is invalid
     * @return amountOut The amount of `toToken` transferred from the Well. Note that if `toToken` charges a fee on transfer, `recipient` may receive less than this amount.
     * @dev Can also be used for tokens without a fee on transfer, but is less gas efficient.
     */
    function swapFromFeeOnTransfer(
        IERC20 fromToken,
        IERC20 toToken,
        uint256 amountIn,
        uint256 minAmountOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256 amountOut);

    /**
     * @notice Gets the amount of one token received for swapping an amount of another token.
     * @param fromToken The token to swap from
     * @param toToken The token to swap to
     * @param amountIn The amount of `fromToken` to spend
     * @return amountOut The amount of `toToken` to receive
     */
    function getSwapOut(IERC20 fromToken, IERC20 toToken, uint256 amountIn) external view returns (uint256 amountOut);

    //////////////////// SWAP: TO ////////////////////

    /**
     * @notice Swaps from a maximum amount of `fromToken` to an exact amount of `toToken`.
     * @param fromToken The token to swap from
     * @param toToken The token to swap to
     * @param maxAmountIn The maximum amount of `fromToken` to spend
     * @param amountOut The amount of `toToken` to receive
     * @param recipient The address to receive `toToken`
     * @param deadline The timestamp after which this operation is invalid
     * @return amountIn The amount of `toToken` received
     */
    function swapTo(
        IERC20 fromToken,
        IERC20 toToken,
        uint256 maxAmountIn,
        uint256 amountOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256 amountIn);

    /**
     * @notice Gets the amount of one token that must be spent to receive an amount of another token during a swap.
     * @param fromToken The token to swap from
     * @param toToken The token to swap to
     * @param amountOut The amount of `toToken` desired
     * @return amountIn The amount of `fromToken` that must be spent
     */
    function getSwapIn(IERC20 fromToken, IERC20 toToken, uint256 amountOut) external view returns (uint256 amountIn);

    //////////////////// SHIFT ////////////////////

    /**
     * @notice Shifts at least `minAmountOut` excess tokens held by the Well into `tokenOut` and delivers to `recipient`.
     * @param tokenOut The token to shift into
     * @param minAmountOut The minimum amount of `tokenOut` to receive
     * @param recipient The address to receive the token
     * @return amountOut The amount of `tokenOut` received
     * @dev Can be used in a multicall using a contract like Pipeline to perform gas efficient swaps.
     * No deadline is needed since this function does not use the user's assets. If adding liquidity in a multicall,
     * then a deadline check can be added to the multicall.
     */
    function shift(IERC20 tokenOut, uint256 minAmountOut, address recipient) external returns (uint256 amountOut);

    /**
     * @notice Calculates the amount of the token out received from shifting excess tokens held by the Well.
     * @param tokenOut The token to shift into
     * @return amountOut The amount of `tokenOut` received
     */
    function getShiftOut(IERC20 tokenOut) external returns (uint256 amountOut);

    //////////////////// ADD LIQUIDITY ////////////////////

    /**
     * @notice Adds liquidity to the Well as multiple tokens in any ratio.
     * @param tokenAmountsIn The amount of each token to add; MUST match the indexing of {Well.tokens}
     * @param minLpAmountOut The minimum amount of LP tokens to receive
     * @param recipient The address to receive the LP tokens
     * @param deadline The timestamp after which this operation is invalid
     * @return lpAmountOut The amount of LP tokens received
     */
    function addLiquidity(
        uint256[] memory tokenAmountsIn,
        uint256 minLpAmountOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256 lpAmountOut);

    /**
     * @notice Adds liquidity to the Well as multiple tokens in any ratio and supports
     * fee on transfer tokens.
     * @param tokenAmountsIn The amount of each token to add; MUST match the indexing of {Well.tokens}
     * @param minLpAmountOut The minimum amount of LP tokens to receive
     * @param recipient The address to receive the LP tokens
     * @param deadline The timestamp after which this operation is invalid
     * @return lpAmountOut The amount of LP tokens received
     * @dev Can also be used for tokens without a fee on transfer, but is less gas efficient.
     */
    function addLiquidityFeeOnTransfer(
        uint256[] memory tokenAmountsIn,
        uint256 minLpAmountOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256 lpAmountOut);

    /**
     * @notice Gets the amount of LP tokens received from adding liquidity as multiple tokens in any ratio.
     * @param tokenAmountsIn The amount of each token to add; MUST match the indexing of {Well.tokens}
     * @return lpAmountOut The amount of LP tokens received
     */
    function getAddLiquidityOut(uint256[] memory tokenAmountsIn) external view returns (uint256 lpAmountOut);

    //////////////////// REMOVE LIQUIDITY: BALANCED ////////////////////

    /**
     * @notice Removes liquidity from the Well as all underlying tokens in a balanced ratio.
     * @param lpAmountIn The amount of LP tokens to burn
     * @param minTokenAmountsOut The minimum amount of each underlying token to receive; MUST match the indexing of {Well.tokens}
     * @param recipient The address to receive the underlying tokens
     * @param deadline The timestamp after which this operation is invalid
     * @return tokenAmountsOut The amount of each underlying token received
     */
    function removeLiquidity(
        uint256 lpAmountIn,
        uint256[] calldata minTokenAmountsOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256[] memory tokenAmountsOut);

    /**
     * @notice Gets the amount of each underlying token received from removing liquidity in a balanced ratio.
     * @param lpAmountIn The amount of LP tokens to burn
     * @return tokenAmountsOut The amount of each underlying token received
     */
    function getRemoveLiquidityOut(uint256 lpAmountIn) external view returns (uint256[] memory tokenAmountsOut);

    //////////////////// REMOVE LIQUIDITY: ONE TOKEN ////////////////////

    /**
     * @notice Removes liquidity from the Well as a single underlying token.
     * @param lpAmountIn The amount of LP tokens to burn
     * @param tokenOut The underlying token to receive
     * @param minTokenAmountOut The minimum amount of `tokenOut` to receive
     * @param recipient The address to receive the underlying tokens
     * @param deadline The timestamp after which this operation is invalid
     * @return tokenAmountOut The amount of `tokenOut` received
     */
    function removeLiquidityOneToken(
        uint256 lpAmountIn,
        IERC20 tokenOut,
        uint256 minTokenAmountOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256 tokenAmountOut);

    /**
     * @notice Gets the amount received from removing liquidity from the Well as a single underlying token.
     * @param lpAmountIn The amount of LP tokens to burn
     * @param tokenOut The underlying token to receive
     * @return tokenAmountOut The amount of `tokenOut` received
     *
     */
    function getRemoveLiquidityOneTokenOut(
        uint256 lpAmountIn,
        IERC20 tokenOut
    ) external view returns (uint256 tokenAmountOut);

    //////////////////// REMOVE LIQUIDITY: IMBALANCED ////////////////////

    /**
     * @notice Removes liquidity from the Well as multiple underlying tokens in any ratio.
     * @param maxLpAmountIn The maximum amount of LP tokens to burn
     * @param tokenAmountsOut The amount of each underlying token to receive; MUST match the indexing of {Well.tokens}
     * @param recipient The address to receive the underlying tokens
     * @return lpAmountIn The amount of LP tokens burned
     */
    function removeLiquidityImbalanced(
        uint256 maxLpAmountIn,
        uint256[] calldata tokenAmountsOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256 lpAmountIn);

    /**
     * @notice Gets the amount of LP tokens to burn from removing liquidity as multiple underlying tokens in any ratio.
     * @param tokenAmountsOut The amount of each underlying token to receive; MUST match the indexing of {Well.tokens}
     * @return lpAmountIn The amount of LP tokens burned
     */
    function getRemoveLiquidityImbalancedIn(uint256[] calldata tokenAmountsOut)
        external
        view
        returns (uint256 lpAmountIn);

    //////////////////// RESERVES ////////////////////

    /**
     * @notice Syncs the Well's reserves with the Well's balances of underlying tokens. If the reserves
     * increase, mints at least `minLpAmountOut` LP Tokens to `recipient`.
     * @param recipient The address to receive the LP tokens
     * @param minLpAmountOut The minimum amount of LP tokens to receive
     * @return lpAmountOut The amount of LP tokens received
     * @dev Can be used in a multicall using a contract like Pipeline to perform gas efficient additions of liquidity.
     * No deadline is needed since this function does not use the user's assets. If adding liquidity in a multicall,
     * then a deadline check can be added to the multicall.
     * If `sync` decreases the Well's reserves, then no LP tokens are minted and `lpAmountOut` must be 0.
     */
    function sync(address recipient, uint256 minLpAmountOut) external returns (uint256 lpAmountOut);

    /**
     * @notice Calculates the amount of LP Tokens received from syncing the Well's reserves with the Well's balances.
     * @return lpAmountOut The amount of LP tokens received
     */
    function getSyncOut() external view returns (uint256 lpAmountOut);

    /**
     * @notice Sends excess tokens held by the Well to the `recipient`.
     * @param recipient The address to send the tokens
     * @return skimAmounts The amount of each token skimmed
     * @dev No deadline is needed since this function does not use the user's assets.
     */
    function skim(address recipient) external returns (uint256[] memory skimAmounts);

    /**
     * @notice Gets the reserves of each token held by the Well.
     */
    function getReserves() external view returns (uint256[] memory reserves);

    /**
     * @notice Returns whether or not the Well is initialized if it requires initialization.
     * If a Well does not require initialization, it should always return `true`.
     */
    function isInitialized() external view returns (bool);
}

File 21 of 54 : IWellFunction.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

/**
 * @title IWellFunction
 * @notice Defines a relationship between token reserves and LP token supply.
 * @dev Well Functions can contain arbitrary logic, but should be deterministic
 * if expected to be used alongside a Pump. When interacing with a Well or
 * Well Function, always verify that the Well Function is valid.
 */
interface IWellFunction {
    /**
     * @notice Calculates the `j`th reserve given a list of `reserves` and `lpTokenSupply`.
     * @param reserves A list of token reserves. The jth reserve will be ignored, but a placeholder must be provided.
     * @param j The index of the reserve to solve for
     * @param lpTokenSupply The supply of LP tokens
     * @param data Extra Well function data provided on every call
     * @return reserve The resulting reserve at the jth index
     * @dev Should round up to ensure that Well reserves are marginally higher to enforce calcLpTokenSupply(...) >= totalSupply()
     */
    function calcReserve(
        uint[] memory reserves,
        uint j,
        uint lpTokenSupply,
        bytes calldata data
    ) external view returns (uint reserve);

    /**
     * @notice Gets the LP token supply given a list of reserves.
     * @param reserves A list of token reserves
     * @param data Extra Well function data provided on every call
     * @return lpTokenSupply The resulting supply of LP tokens
     * @dev Should round down to ensure so that the Well Token supply is marignally lower to enforce calcLpTokenSupply(...) >= totalSupply()
     */
    function calcLpTokenSupply(
        uint[] memory reserves,
        bytes calldata data
    ) external view returns (uint lpTokenSupply);

    /**
     * @notice Calculates the amount of each reserve token underlying a given amount of LP tokens.
     * @param lpTokenAmount An amount of LP tokens
     * @param reserves A list of token reserves
     * @param lpTokenSupply The current supply of LP tokens
     * @param data Extra Well function data provided on every call
     * @return underlyingAmounts The amount of each reserve token that underlies the LP tokens
     * @dev The constraint totalSupply() <= calcLPTokenSupply(...) must be held in the case where
     * `lpTokenAmount` LP tokens are burned in exchanged for `underlyingAmounts`. If the constraint
     * does not hold, then the Well Function is invalid.
     */
    function calcLPTokenUnderlying(
        uint lpTokenAmount,
        uint[] memory reserves,
        uint lpTokenSupply,
        bytes calldata data
    ) external view returns (uint[] memory underlyingAmounts);

    /**
     * @notice Returns the name of the Well function.
     */
    function name() external view returns (string memory);

    /**
     * @notice Returns the symbol of the Well function.
     */
    function symbol() external view returns (string memory);
}

File 22 of 54 : IInstantaneousPump.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

/**
 * @title Instantaneous Pumps provide an Oracle for instantaneous reserves.
 */
interface IInstantaneousPump {
    /**
     * @notice Reads instantaneous reserves from the Pump
     * @param well The address of the Well
     * @return reserves The instantaneous balanecs tracked by the Pump
     */
    function readInstantaneousReserves(
        address well,
        bytes memory data
    ) external view returns (uint[] memory reserves);
}

File 23 of 54 : IChainlinkAggregator.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;

interface IChainlinkAggregator {
  function decimals() external view returns (uint8);

  function description() external view returns (string memory);

  function version() external view returns (uint256);

  // getRoundData and latestRoundData should both raise "No data present"
  // if they do not have data to report, instead of returning unset values
  // which could be misinterpreted as actual reported values.
  function getRoundData(uint80 _roundId)
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );
}

File 24 of 54 : 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 25 of 54 : 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 26 of 54 : 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 27 of 54 : 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 28 of 54 : IProxyAdmin.sol
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity =0.7.6;
interface IProxyAdmin {
    function upgrade(address proxy, address implementation) external;
}

File 29 of 54 : LibConvert.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {LibCurveConvert} from "./LibCurveConvert.sol";
import {LibUnripeConvert} from "./LibUnripeConvert.sol";
import {LibLambdaConvert} from "./LibLambdaConvert.sol";
import {LibConvertData} from "./LibConvertData.sol";
import {LibWellConvert} from "./LibWellConvert.sol";
import {LibWell} from "contracts/libraries/Well/LibWell.sol";
import {C} from "contracts/C.sol";

/**
 * @title LibConvert
 * @author Publius
 */
library LibConvert {
    using SafeMath for uint256;
    using LibConvertData for bytes;
    using LibWell for address;

    /**
     * @notice Takes in bytes object that has convert input data encoded into it for a particular convert for
     * a specified pool and returns the in and out convert amounts and token addresses and bdv
     * @param convertData Contains convert input parameters for a specified convert
     */
    function convert(bytes calldata convertData)
        internal
        returns (
            address tokenOut,
            address tokenIn,
            uint256 amountOut,
            uint256 amountIn
        )
    {
        LibConvertData.ConvertKind kind = convertData.convertKind();

        if (kind == LibConvertData.ConvertKind.BEANS_TO_CURVE_LP) {
            (tokenOut, tokenIn, amountOut, amountIn) = LibCurveConvert
                .convertBeansToLP(convertData);
        } else if (kind == LibConvertData.ConvertKind.CURVE_LP_TO_BEANS) {
            (tokenOut, tokenIn, amountOut, amountIn) = LibCurveConvert
                .convertLPToBeans(convertData);
        } else if (kind == LibConvertData.ConvertKind.UNRIPE_BEANS_TO_UNRIPE_LP) {
            (tokenOut, tokenIn, amountOut, amountIn) = LibUnripeConvert
                .convertBeansToLP(convertData);
        } else if (kind == LibConvertData.ConvertKind.UNRIPE_LP_TO_UNRIPE_BEANS) {
            (tokenOut, tokenIn, amountOut, amountIn) = LibUnripeConvert
                .convertLPToBeans(convertData);
        } else if (kind == LibConvertData.ConvertKind.LAMBDA_LAMBDA) {
            (tokenOut, tokenIn, amountOut, amountIn) = LibLambdaConvert
                .convert(convertData);
        } else if (kind == LibConvertData.ConvertKind.BEANS_TO_WELL_LP) {
            (tokenOut, tokenIn, amountOut, amountIn) = LibWellConvert
                .convertBeansToLP(convertData);
        } else if (kind == LibConvertData.ConvertKind.WELL_LP_TO_BEANS) {
            (tokenOut, tokenIn, amountOut, amountIn) = LibWellConvert
                .convertLPToBeans(convertData);
        } else {
            revert("Convert: Invalid payload");
        }
    }

    function getMaxAmountIn(address tokenIn, address tokenOut)
        internal
        view
        returns (uint256)
    {
        /// BEAN:3CRV LP -> BEAN
        if (tokenIn == C.CURVE_BEAN_METAPOOL && tokenOut == C.BEAN)
            return LibCurveConvert.lpToPeg(C.CURVE_BEAN_METAPOOL);
        
        /// BEAN -> BEAN:3CRV LP
        if (tokenIn == C.BEAN && tokenOut == C.CURVE_BEAN_METAPOOL)
            return LibCurveConvert.beansToPeg(C.CURVE_BEAN_METAPOOL);
        
        /// urBEAN:3CRV LP -> urBEAN
        if (tokenIn == C.UNRIPE_LP && tokenOut == C.UNRIPE_BEAN)
            return LibUnripeConvert.lpToPeg();

        /// urBEAN -> urBEAN:3CRV LP
        if (tokenIn == C.UNRIPE_BEAN && tokenOut == C.UNRIPE_LP)
            return LibUnripeConvert.beansToPeg();

        // Lambda -> Lambda
        if (tokenIn == tokenOut) 
            return type(uint256).max;

        // Bean -> Well LP Token
        if (tokenIn == C.BEAN && tokenOut.isWell())
            return LibWellConvert.beansToPeg(tokenOut);

        // Well LP Token -> Bean
        if (tokenIn.isWell() && tokenOut == C.BEAN)
            return LibWellConvert.lpToPeg(tokenIn);

        revert("Convert: Tokens not supported");
    }

    function getAmountOut(address tokenIn, address tokenOut, uint256 amountIn)
        internal
        view
        returns (uint256)
    {
        /// BEAN:3CRV LP -> BEAN
        if (tokenIn == C.CURVE_BEAN_METAPOOL && tokenOut == C.BEAN)
            return LibCurveConvert.getBeanAmountOut(C.CURVE_BEAN_METAPOOL, amountIn);
        
        /// BEAN -> BEAN:3CRV LP
        if (tokenIn == C.BEAN && tokenOut == C.CURVE_BEAN_METAPOOL)
            return LibCurveConvert.getLPAmountOut(C.CURVE_BEAN_METAPOOL, amountIn);

        /// urBEAN:3CRV LP -> urBEAN
        if (tokenIn == C.UNRIPE_LP && tokenOut == C.UNRIPE_BEAN)
            return LibUnripeConvert.getBeanAmountOut(amountIn);
        
        /// urBEAN -> urBEAN:3CRV LP
        if (tokenIn == C.UNRIPE_BEAN && tokenOut == C.UNRIPE_LP)
            return LibUnripeConvert.getLPAmountOut(amountIn);
        
        // Lambda -> Lambda
        if (tokenIn == tokenOut)
            return amountIn;

        // Bean -> Well LP Token
        if (tokenIn == C.BEAN && tokenOut.isWell())
            return LibWellConvert.getLPAmountOut(tokenOut, amountIn);

        // Well LP Token -> Bean
        if (tokenIn.isWell() && tokenOut == C.BEAN)
            return LibWellConvert.getBeanAmountOut(tokenIn, amountIn);

        revert("Convert: Tokens not supported");
    }
}

File 30 of 54 : LibConvertData.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

/**
 * @title LibConvertData
 * @author LeoFib
 */
library LibConvertData {
    // In order to preserve backwards compatibility, make sure new kinds are added at the end of the enum.
    enum ConvertKind {
        BEANS_TO_CURVE_LP,
        CURVE_LP_TO_BEANS,
        UNRIPE_BEANS_TO_UNRIPE_LP,
        UNRIPE_LP_TO_UNRIPE_BEANS,
        LAMBDA_LAMBDA,
        BEANS_TO_WELL_LP,
        WELL_LP_TO_BEANS
    }

    /// @notice Decoder for the Convert Enum
    function convertKind(bytes memory self)
        internal
        pure
        returns (ConvertKind)
    {
        return abi.decode(self, (ConvertKind));
    }

    /// @notice Decoder for the addLPInBeans Convert
    function basicConvert(bytes memory self)
        internal
        pure
        returns (uint256 amountIn, uint256 minAmontOut)
    {
        (, amountIn, minAmontOut) = abi.decode(
            self,
            (ConvertKind, uint256, uint256)
        );
    }

    /// @notice Decoder for the addLPInBeans Convert
    function convertWithAddress(bytes memory self)
        internal
        pure
        returns (
            uint256 amountIn,
            uint256 minAmontOut,
            address token
        )
    {
        (, amountIn, minAmontOut, token) = abi.decode(
            self,
            (ConvertKind, uint256, uint256, address)
        );
    }

    function lambdaConvert(bytes memory self)
        internal
        pure
        returns (uint256 amount, address token)
    {
        (, amount, token) = abi.decode(self, (ConvertKind, uint256, address));
    }
}

File 31 of 54 : LibCurveConvert.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {ICurvePool} from "contracts/interfaces/ICurve.sol";
import {LibAppStorage, AppStorage} from "../LibAppStorage.sol";
import {LibConvertData} from "./LibConvertData.sol";
import {LibMetaCurveConvert} from "./LibMetaCurveConvert.sol";
import {C} from "contracts/C.sol";

/**
 * @title Curve Convert Library
 * @notice Contains Functions to convert from/to Curve LP tokens to/from Beans
 * in the direction of the Peg.
 **/
library LibCurveConvert {
    using SafeMath for uint256;
    using LibConvertData for bytes;

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

    /**
     * @notice Calculate the number of BEAN needed to be added as liquidity to return `pool` back to peg.
     * @dev
     *   Assumes that BEAN is the first token in the pool.
     *   Returns 0 if returns peg.
     */
    function beansToPeg(address pool) internal view returns (uint256 beans) {
        uint256[2] memory balances = ICurvePool(pool).get_balances();
        uint256 xp1 = _getBeansAtPeg(pool, balances);
        if (xp1 <= balances[0]) return 0;
        beans = xp1.sub(balances[0]);
    }

    /**
     * @notice Calculate the amount of liquidity needed to be removed as Beans to return `pool` back to peg.
     * @dev Returns 0 if above peg.
     */
    function lpToPeg(address pool) internal view returns (uint256 lp) {
        uint256[2] memory balances = ICurvePool(pool).get_balances();
        uint256 xp1 = _getBeansAtPeg(pool, balances);
        if (balances[0] <= xp1) return 0;
        return LibMetaCurveConvert.lpToPeg(balances, xp1);
    }

    /**
     * @param pool The address of the Curve pool where `amountIn` will be withdrawn
     * @param amountIn The amount of the LP token of `pool` to remove as BEAN
     * @return beans The amount of BEAN received for removing `amountIn` LP tokens.
     * @dev Assumes that i=0 corresponds to BEAN.
     */
    function getBeanAmountOut(address pool, uint256 amountIn) internal view returns(uint256 beans) {
        beans = ICurvePool(pool).calc_withdraw_one_coin(amountIn, 0); // i=0 -> BEAN
    }

    /**
     * @param pool The address of the Curve pool where `amountIn` will be deposited
     * @param amountIn The amount of BEAN to deposit into `pool`
     * @return lp The amount of LP received for depositing BEAN.
     * @dev Assumes that i=0 corresponds to BEAN.
     */
    function getLPAmountOut(address pool, uint256 amountIn) internal view returns(uint256 lp) {
        lp = ICurvePool(pool).calc_token_amount([amountIn, 0], true); // i=0 -> BEAN
    }

    //////////////////// CURVE CONVERT: KINDS ////////////////////

    /**
     * @notice Decodes convert data and increasing deltaB by removing liquidity as Beans.
     * @param convertData Contains convert input parameters for a Curve AddLPInBeans convert
     */
    function convertLPToBeans(bytes memory convertData)
        internal
        returns (
            address tokenOut,
            address tokenIn,
            uint256 amountOut,
            uint256 amountIn
        )
    {
        (uint256 lp, uint256 minBeans, address pool) = convertData
            .convertWithAddress();
        (amountOut, amountIn) = curveRemoveLPTowardsPeg(lp, minBeans, pool);
        tokenOut = C.BEAN;
        tokenIn = pool;
    }

    /**
     * @notice Decodes convert data and decreases deltaB by adding Beans as 1-sided liquidity.
     * @param convertData Contains convert input parameters for a Curve AddBeansInLP convert
     */
    function convertBeansToLP(bytes memory convertData)
        internal
        returns (
            address tokenOut,
            address tokenIn,
            uint256 amountOut,
            uint256 amountIn
        )
    {
        (uint256 beans, uint256 minLP, address pool) = convertData
            .convertWithAddress();
        (amountOut, amountIn) = curveAddLiquidityTowardsPeg(
            beans,
            minLP,
            pool
        );
        tokenOut = pool;
        tokenIn = C.BEAN;
    }

    //////////////////// CURVE CONVERT: LOGIC ////////////////////

    /**
     * @notice Increase deltaB by adding Beans as liquidity via Curve.
     * @dev deltaB <≈ 0 after the convert
     * @param beans The amount of beans to convert to Curve LP
     * @param minLP The minimum amount of Curve LP to receive
     * @param pool The address of the Curve pool to add to
     */
    function curveAddLiquidityTowardsPeg(
        uint256 beans,
        uint256 minLP,
        address pool
    ) internal returns (uint256 lp, uint256 beansConverted) {
        uint256 beansTo = beansToPeg(pool);
        require(beansTo > 0, "Convert: P must be >= 1.");
        beansConverted = beans > beansTo ? beansTo : beans;
        lp = ICurvePool(pool).add_liquidity([beansConverted, 0], minLP);
    }

    /**
     * @notice Decrease deltaB by removing LP as Beans via Curve.
     * @dev deltaB >≈ 0 after the convert
     * @param lp The amount of Curve LP to be removed
     * @param minBeans The minimum amount of Beans to receive
     * @param pool The address of the Curve pool to remove from
     */
    function curveRemoveLPTowardsPeg(
        uint256 lp,
        uint256 minBeans,
        address pool
    ) internal returns (uint256 beans, uint256 lpConverted) {
        uint256 lpTo = lpToPeg(pool);
        require(lpTo > 0, "Convert: P must be < 1.");
        lpConverted = lp > lpTo ? lpTo : lp;
        beans = ICurvePool(pool).remove_liquidity_one_coin(
            lpConverted,
            0,
            minBeans
        );
    }

    //////////////////// INTERNAL ////////////////////
    
    function _getBeansAtPeg(
        address pool,
        uint256[2] memory balances
    ) internal view returns (uint256) {
        if (pool == C.CURVE_BEAN_METAPOOL) {
            return LibMetaCurveConvert.beansAtPeg(balances);
        }

        revert("Convert: Not a whitelisted Curve pool.");
    }
}

File 32 of 54 : LibLambdaConvert.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import {LibConvertData} from "./LibConvertData.sol";

/**
 * @title LibLambdaConvert
 * @author Publius
 */
library LibLambdaConvert {
    using LibConvertData for bytes;

    function convert(bytes memory convertData)
        internal
        pure
        returns (
            address tokenOut,
            address tokenIn,
            uint256 amountOut,
            uint256 amountIn
        )
    {
        (amountIn, tokenIn) = convertData.lambdaConvert();
        tokenOut = tokenIn;
        amountOut = amountIn;
    }
}

File 33 of 54 : LibMetaCurveConvert.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {LibConvertData} from "./LibConvertData.sol";
import {LibBeanMetaCurve} from "../Curve/LibBeanMetaCurve.sol";
import {LibCurve} from "../Curve/LibCurve.sol";
import {LibAppStorage} from "../LibAppStorage.sol";
import {C} from "contracts/C.sol";

/**
 * @title LibMetaCurveConvert
 * @author Publius
 */
library LibMetaCurveConvert {
    using SafeMath for uint256;
    using LibConvertData for bytes;

    uint256 constant private N_COINS = 2;
    uint256 constant private FEED2 = 2000000;
    uint256 constant private ADMIN_FEE = 5e9;
    uint256 constant private FEE_DENOMINATOR = 1e10;

    /**
     * @notice Calculate the amount of BEAN that would exist in a Curve metapool
     * if it were "at peg", i.e. if there was 1 BEAN per 1 USD of 3CRV.
     * @dev Assumes that `balances[1]` is 3CRV.
     */
    function beansAtPeg(uint256[2] memory balances)
        internal
        view
        returns (uint256 beans)
    {
        return balances[1].mul(C.curve3Pool().get_virtual_price()).div(1e30);
    }

    function lpToPeg(uint256[2] memory balances, uint256 atPeg) internal view returns (uint256 lp) {
        uint256 a = C.curveMetapool().A_precise();
        uint256[2] memory xp = LibBeanMetaCurve.getXP(balances);
        uint256 d0 = LibCurve.getD(xp, a);
        uint256 toPeg = balances[0].sub(atPeg);
        toPeg = _toPegWithFee(toPeg, balances, d0, a);
        lp = _calcLPTokenAmount(toPeg, balances, d0, a);
    }

    //////////////////// INTERNAL ////////////////////

    function _calcLPTokenAmount(
        uint256 amount,
        uint256[2] memory balances,
        uint256 D0,
        uint256 a
    ) internal view returns (uint256) {
        balances[0] = balances[0].sub(amount);
        uint256[2] memory xp = LibBeanMetaCurve.getXP(balances);
        uint256 D1 = LibCurve.getD(xp, a);
        uint256 diff = D0.sub(D1);
        return diff.mul(C.curveMetapool().totalSupply()).div(D0);
    }

    function _toPegWithFee(
        uint256 amount,
        uint256[2] memory balances,
        uint256 D0,
        uint256 a
    ) internal view returns (uint256) {
        uint256[2] memory xp = LibBeanMetaCurve.getXP(balances);
        uint256 new_y = LibBeanMetaCurve.getXP0(balances[0].sub(amount));
        uint256 D1 = LibCurve.getD([new_y, xp[1]], a);

        uint256[N_COINS] memory xp_reduced;
        uint256 dx_expected = xp[0].mul(D1).div(D0).sub(new_y);
        xp_reduced[0] = xp[0].sub(FEED2.mul(dx_expected) / FEE_DENOMINATOR);

        dx_expected = xp[1].sub(xp[1].mul(D1).div(D0));
        xp_reduced[1] = xp[1].sub(FEED2.mul(dx_expected) / FEE_DENOMINATOR);

        uint256 yd = LibCurve.getYD(a, 0, xp_reduced, D1);
        uint256 dy = xp_reduced[0].sub(yd);
        dy = LibBeanMetaCurve.getX0(dy.sub(1));
        uint256 dy_0 = LibBeanMetaCurve.getX0(xp[0].sub(new_y));

        return dy_0.add(
            dy_0.sub(dy).mul(ADMIN_FEE).div(FEE_DENOMINATOR)
        );
    }
}

File 34 of 54 : LibUnripeConvert.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import {C} from "contracts/C.sol";
import {IBean} from "contracts/interfaces/IBean.sol";
import {LibWellConvert} from "./LibWellConvert.sol";
import {LibUnripe} from "../LibUnripe.sol";
import {LibConvertData} from "./LibConvertData.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";

/**
 * @title LibUnripeConvert
 * @author Publius
 */
library LibUnripeConvert {
    using LibConvertData for bytes;
    using SafeMath for uint256;

    function convertLPToBeans(bytes memory convertData)
        internal
        returns (
            address tokenOut,
            address tokenIn,
            uint256 amountOut,
            uint256 amountIn
        )
    {
        tokenOut = C.UNRIPE_BEAN;
        tokenIn = C.UNRIPE_LP;
        (uint256 lp, uint256 minBeans) = convertData.basicConvert();

        uint256 minAmountOut = LibUnripe
            .unripeToUnderlying(tokenOut, minBeans)
            .mul(LibUnripe.percentLPRecapped())
            .div(LibUnripe.percentBeansRecapped());

        (
            uint256 outUnderlyingAmount,
            uint256 inUnderlyingAmount
        ) = LibWellConvert._wellRemoveLiquidityTowardsPeg(
                LibUnripe.unripeToUnderlying(tokenIn, lp),
                minAmountOut,
                C.BEAN_ETH_WELL
            );

        amountIn = LibUnripe.underlyingToUnripe(tokenIn, inUnderlyingAmount);
        LibUnripe.removeUnderlying(tokenIn, inUnderlyingAmount);
        IBean(tokenIn).burn(amountIn);

        amountOut = LibUnripe
            .underlyingToUnripe(tokenOut, outUnderlyingAmount)
            .mul(LibUnripe.percentBeansRecapped())
            .div(LibUnripe.percentLPRecapped());
        LibUnripe.addUnderlying(tokenOut, outUnderlyingAmount);
        IBean(tokenOut).mint(address(this), amountOut);
    }

    function convertBeansToLP(bytes memory convertData)
        internal
        returns (
            address tokenOut,
            address tokenIn,
            uint256 amountOut,
            uint256 amountIn
        )
    {
        tokenIn = C.UNRIPE_BEAN;
        tokenOut = C.UNRIPE_LP;
        (uint256 beans, uint256 minLP) = convertData.basicConvert();

        uint256 minAmountOut = LibUnripe
            .unripeToUnderlying(tokenOut, minLP)
            .mul(LibUnripe.percentBeansRecapped())
            .div(LibUnripe.percentLPRecapped());

        (
            uint256 outUnderlyingAmount,
            uint256 inUnderlyingAmount
        ) = LibWellConvert._wellAddLiquidityTowardsPeg(
                LibUnripe.unripeToUnderlying(tokenIn, beans),
                minAmountOut,
                C.BEAN_ETH_WELL
            );

        amountIn = LibUnripe.underlyingToUnripe(tokenIn, inUnderlyingAmount);
        LibUnripe.removeUnderlying(tokenIn, inUnderlyingAmount);
        IBean(tokenIn).burn(amountIn);

        amountOut = LibUnripe
            .underlyingToUnripe(tokenOut, outUnderlyingAmount)
            .mul(LibUnripe.percentLPRecapped())
            .div(LibUnripe.percentBeansRecapped());
        LibUnripe.addUnderlying(tokenOut, outUnderlyingAmount);
        IBean(tokenOut).mint(address(this), amountOut);
    }

    function beansToPeg() internal view returns (uint256 beans) {
        uint256 underlyingBeans = LibWellConvert.beansToPeg(
            C.BEAN_ETH_WELL
        );
        beans = LibUnripe.underlyingToUnripe(
            C.UNRIPE_BEAN,
            underlyingBeans
        );
    }

    function lpToPeg() internal view returns (uint256 lp) {
        uint256 underlyingLP = LibWellConvert.lpToPeg(
            C.BEAN_ETH_WELL
        );
        lp = LibUnripe.underlyingToUnripe(C.UNRIPE_LP, underlyingLP);
    }

    function getLPAmountOut(uint256 amountIn)
        internal
        view
        returns (uint256 lp)
    {
        uint256 beans = LibUnripe.unripeToUnderlying(
            C.UNRIPE_BEAN,
            amountIn
        );
        lp = LibWellConvert.getLPAmountOut(C.BEAN_ETH_WELL, beans);
        lp = LibUnripe
            .underlyingToUnripe(C.UNRIPE_LP, lp)
            .mul(LibUnripe.percentLPRecapped())
            .div(LibUnripe.percentBeansRecapped());
    }

    function getBeanAmountOut(uint256 amountIn)
        internal
        view
        returns (uint256 bean)
    {
        uint256 lp = LibUnripe.unripeToUnderlying(
            C.UNRIPE_LP,
            amountIn
        );
        bean = LibWellConvert.getBeanAmountOut(C.BEAN_ETH_WELL, lp);
        bean = LibUnripe
            .underlyingToUnripe(C.UNRIPE_BEAN, bean)
            .mul(LibUnripe.percentBeansRecapped())
            .div(LibUnripe.percentLPRecapped());
    }
}

File 35 of 54 : LibWellConvert.sol
/*
 SPDX-License-Identifier: MIT
*/

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {LibConvertData} from "contracts/libraries/Convert/LibConvertData.sol";
import {LibWell} from "contracts/libraries/Well/LibWell.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {C} from "contracts/C.sol";
import {Call, IWell} from "contracts/interfaces/basin/IWell.sol";
import {IBeanstalkWellFunction} from "contracts/interfaces/basin/IBeanstalkWellFunction.sol";

/**
 * @title Well Convert Library
 * @notice Contains Functions to convert from/to Well LP tokens to/from Beans
 * in the direction of the Peg.
 **/
library LibWellConvert {
    using SafeMath for uint256;
    using LibConvertData for bytes;

    /**
     * @dev Calculates the maximum amount of Beans that can be
     * convert to the LP Token of a given `well` while maintaining a delta B >= 0.
     */
    function beansToPeg(address well) internal view returns (uint256 beans) {
        (beans, ) = _beansToPeg(well);
    }

    /**
     * An internal version of `beansToPeg` that always returns the
     * index of the Bean token in a given `well`.
     */
    function _beansToPeg(address well) internal view returns (uint256 beans, uint256 beanIndex) {
        IERC20[] memory tokens = IWell(well).tokens();
        uint256[] memory reserves = IWell(well).getReserves();
        Call memory wellFunction = IWell(well).wellFunction();
        uint256[] memory ratios; bool success;
        (ratios, beanIndex, success) = LibWell.getRatiosAndBeanIndex(tokens);
        // If the USD Oracle oracle call fails, the convert should not be allowed.
        require(success, "Convert: USD Oracle failed");

        uint256 beansAtPeg = IBeanstalkWellFunction(wellFunction.target).calcReserveAtRatioLiquidity(
            reserves,
            beanIndex,
            ratios,
            wellFunction.data
        );

        if (beansAtPeg <= reserves[beanIndex]) return (0, beanIndex);
        // SafeMath is unnecessary as above line performs the check
        beans = beansAtPeg - reserves[beanIndex];
    }

    /**
     * @dev Calculates the maximum amount of LP Tokens of a given `well` that can be 
     * converted to Beans while maintaining a delta B <= 0.
     */
    function lpToPeg(address well) internal view returns (uint256 lp) {
        IERC20[] memory tokens = IWell(well).tokens();
        uint256[] memory reserves = IWell(well).getReserves();
        Call memory wellFunction = IWell(well).wellFunction();
        (uint256[] memory ratios, uint256 beanIndex, bool success) = LibWell.getRatiosAndBeanIndex(tokens);
        // If the USD Oracle oracle call fails, the convert should not be allowed.
        require(success, "Convert: USD Oracle failed");

        uint256 beansAtPeg = IBeanstalkWellFunction(wellFunction.target).calcReserveAtRatioLiquidity(
            reserves,
            beanIndex,
            ratios,
            wellFunction.data
        );

        if (reserves[beanIndex] <= beansAtPeg) return 0;

        uint256 lpSupplyNow = IBeanstalkWellFunction(wellFunction.target).calcLpTokenSupply(
            reserves,
            wellFunction.data
        );

        reserves[beanIndex] = beansAtPeg;
        return lpSupplyNow.sub(IBeanstalkWellFunction(wellFunction.target).calcLpTokenSupply(
            reserves,
            wellFunction.data
        ));
    }

    /**
     * @dev Calculates the amount of Beans recieved from converting
     * `amountIn` LP Tokens of a given `well`.
     */
    function getBeanAmountOut(address well, uint256 amountIn) internal view returns(uint256 beans) {
        beans = IWell(well).getRemoveLiquidityOneTokenOut(amountIn, IERC20(C.BEAN));
    }

    /**
     * @dev Calculates the amount of LP Tokens of a given `well` recieved from converting
     * `amountIn` Beans.
     */
    function getLPAmountOut(address well, uint256 amountIn) internal view returns(uint256 lp) {
        IERC20[] memory tokens = IWell(well).tokens();
        uint256[] memory amounts = new uint256[](tokens.length);
        amounts[LibWell.getBeanIndex(tokens)] = amountIn;
        lp = IWell(well).getAddLiquidityOut(amounts);
    }

    /**
     * @notice Converts `lp` LP Tokens of a given `well` into at least `minBeans` Beans
     * while ensuring that delta B <= 0 in the Bean:3Crv Curve Metapool.
     * @param convertData Contains the encoding of `lp`, `minBeans` and `well`.
     * @return tokenOut The token to convert to.
     * @return tokenIn The token to convert from
     * @return amountOut The number of `tokenOut` convert to
     * @return amountIn The number of `tokenIn` converted from
     */
    function convertLPToBeans(bytes memory convertData)
        internal
        returns (
            address tokenOut,
            address tokenIn,
            uint256 amountOut,
            uint256 amountIn
        )
    {
        (uint256 lp, uint256 minBeans, address well) = convertData.convertWithAddress();

        tokenOut = C.BEAN;
        tokenIn = well;

        (amountOut, amountIn) = _wellRemoveLiquidityTowardsPeg(lp, minBeans, well);
    }

    /**
     * @dev Removes Liquidity as Beans with the constraint that delta B <= 0.
     */
    function _wellRemoveLiquidityTowardsPeg(
        uint256 lp,
        uint256 minBeans,
        address well
    ) internal returns (uint256 beans, uint256 lpConverted) {
        uint256 maxLp = lpToPeg(well);
        require(maxLp > 0, "Convert: P must be < 1.");
        lpConverted = lp > maxLp ? maxLp : lp;
        beans = IWell(well).removeLiquidityOneToken(
            lpConverted,
            C.bean(),
            minBeans,
            address(this),
            block.timestamp
        );
    }

    /**
     * @notice Converts `beans` Beans into at least `minLP` LP Tokens of a given `well`
     * while ensuring that delta B >= 0 in the Bean:3Crv Curve Metapool.
     * @param convertData Contains the encoding of `beans`, `minLp` and `well`.
     * @return tokenOut The token to convert to.
     * @return tokenIn The token to convert from
     * @return amountOut The number of `tokenOut` convert to
     * @return amountIn The number of `tokenIn` converted from
     */
    function convertBeansToLP(bytes memory convertData)
        internal
        returns (
            address tokenOut,
            address tokenIn,
            uint256 amountOut,
            uint256 amountIn
        )
    {
        (uint256 beans, uint256 minLP, address well) = convertData
            .convertWithAddress();
    
        tokenOut = well;
        tokenIn = C.BEAN;

        (amountOut, amountIn) = _wellAddLiquidityTowardsPeg(
            beans,
            minLP,
            well
        );
    }

    /**
     * @dev Adds as Beans Liquidity with the constraint that delta B >= 0.
     */
    function _wellAddLiquidityTowardsPeg(
        uint256 beans,
        uint256 minLP,
        address well
    ) internal returns (uint256 lp, uint256 beansConverted) {
        (uint256 maxBeans, uint beanIndex) = _beansToPeg(well);
        require(maxBeans > 0, "Convert: P must be >= 1.");
        beansConverted = beans > maxBeans ? maxBeans : beans;
        IERC20[] memory tokens = IWell(well).tokens();
        C.bean().transfer(well, beans);
        lp = IWell(well).sync(
            address(this),
            minLP
        );
    }
}

File 36 of 54 : LibBeanMetaCurve.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {LibMetaCurve, IMeta3Curve} from "./LibMetaCurve.sol";
import {LibCurve} from "./LibCurve.sol";
import "contracts/C.sol";

/**
 * @title LibBeanMetaCurve
 * @author Publius
 * @notice Calculates BDV and deltaB for the BEAN:3CRV Metapool.
 */
library LibBeanMetaCurve {
    using SafeMath for uint256;

    uint256 private constant RATE_MULTIPLIER = 1e12; // Bean has 6 Decimals => 1e(18 - delta decimals)
    uint256 private constant PRECISION = 1e18;
    uint256 private constant i = 0;
    uint256 private constant j = 1;

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

    /**
     * @param amount An amount of the BEAN:3CRV LP token.
     * @dev Calculates the current BDV of BEAN given the balances in the BEAN:3CRV
     * Metapool. NOTE: assumes that `balances[0]` is BEAN.
     */
    function bdv(uint256 amount) internal view returns (uint256) {
        // By using previous balances and the virtual price, we protect against flash loan
        uint256[2] memory balances = IMeta3Curve(C.CURVE_BEAN_METAPOOL).get_previous_balances();
        uint256 virtualPrice = C.curveMetapool().get_virtual_price();
        uint256[2] memory xp = LibMetaCurve.getXP(balances, RATE_MULTIPLIER);

        uint256 a = C.curveMetapool().A_precise();
        uint256 D = LibCurve.getD(xp, a);
        uint256 price = LibCurve.getPrice(xp, a, D, RATE_MULTIPLIER);
        uint256 totalSupply = (D * PRECISION) / virtualPrice;
        uint256 beanValue = balances[0].mul(amount).div(totalSupply);
        uint256 curveValue = xp[1].mul(amount).div(totalSupply).div(price);
        
        return beanValue.add(curveValue);
    }

    function getDeltaB() internal view returns (int256 deltaB) {
        uint256[2] memory balances = C.curveMetapool().get_balances();
        uint256 d = getDFroms(balances);
        deltaB = getDeltaBWithD(balances[0], d);
    }
    
    function getDeltaBWithD(uint256 balance, uint256 D)
        internal
        pure
        returns (int256 deltaB)
    {
        uint256 pegBeans = D / 2 / RATE_MULTIPLIER;
        deltaB = int256(pegBeans) - int256(balance);
    }

    //////////////////// CURVE HELPERS ////////////////////

    /**
     * @dev D = the number of LP tokens times the virtual price.
     * LP supply = D / virtual price. D increases as pool accumulates fees.
     * D = number of stable tokens in the pool when the pool is balanced. 
     * 
     * Rate multiplier for BEAN is 1e12.
     * Rate multiplier for 3CRV is virtual price.
     */
    function getDFroms(uint256[2] memory balances)
        internal
        view
        returns (uint256)
    {
        return LibMetaCurve.getDFroms(
            C.CURVE_BEAN_METAPOOL,
            balances,
            RATE_MULTIPLIER
        );
    }

    /**
     * @dev `xp = balances * RATE_MULTIPLIER`
     */
    function getXP(uint256[2] memory balances)
        internal
        view
        returns (uint256[2] memory xp)
    {
        xp = LibMetaCurve.getXP(balances, RATE_MULTIPLIER);
    }

    /**
     * @dev Convert from `balance` -> `xp0`, which is scaled up by `RATE_MULTIPLIER`.
     */
    function getXP0(uint256 balance)
        internal
        pure
        returns (uint256 xp0)
    {
        xp0 = balance.mul(RATE_MULTIPLIER);
    }

    /**
     * @dev Convert from `xp0` -> `balance`, which is scaled down by `RATE_MULTIPLIER`.
     */
    function getX0(uint256 xp0)
        internal
        pure
        returns (uint256 balance0)
    {
        balance0 = xp0.div(RATE_MULTIPLIER);
    }
}

File 37 of 54 : LibCurve.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

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

/**
 * @title LibCurve
 * @author Publius
 * @notice Low-level Curve swap math for a 2-token StableSwap pool.
 */
library LibCurve {
    using SafeMath for uint256;

    uint256 private constant A_PRECISION = 100;
    uint256 private constant N_COINS = 2;
    uint256 private constant PRECISION = 1e18;
    uint256 private constant i = 0;
    uint256 private constant j = 1;

    /**
     * @dev Find the change in token `j` given a change in token `i`.
     */
    function getPrice(
        uint256[2] memory xp,
        uint256 a,
        uint256 D,
        uint256 padding
    ) internal pure returns (uint256) {
        uint256 x = xp[i] + padding;
        uint256 y = getY(x, xp, a, D);
        uint256 dy = xp[j] - y - 1;
        return dy;
    }

    function getPrice(
        uint256[2] memory xp,
        uint256[2] memory rates,
        uint256 a,
        uint256 D
    ) internal pure returns (uint256) {
        uint256 x = xp[i] + ((1 * rates[i]) / PRECISION);
        uint256 y = getY(x, xp, a, D);
        uint256 dy = xp[j] - y - 1;
        return dy / 1e6;
    }

    function getY(
        uint256 x,
        uint256[2] memory xp,
        uint256 a,
        uint256 D
    ) internal pure returns (uint256 y) {
        // Solution is taken from pool contract: 0xc9C32cd16Bf7eFB85Ff14e0c8603cc90F6F2eE49
        uint256 S_ = 0;
        uint256 _x = 0;
        uint256 y_prev = 0;
        uint256 c = D;
        uint256 Ann = a * N_COINS;

        for (uint256 _i; _i < N_COINS; ++_i) {
            if (_i == i) _x = x;
            else if (_i != j) _x = xp[_i];
            else continue;
            S_ += _x;
            c = (c * D) / (_x * N_COINS);
        }

        c = (c * D * A_PRECISION) / (Ann * N_COINS);
        uint256 b = S_ + (D * A_PRECISION) / Ann; // - D
        y = D;

        for (uint256 _i; _i < 255; ++_i) {
            y_prev = y;
            y = (y * y + c) / (2 * y + b - D);
            if (y > y_prev && y - y_prev <= 1) return y;
            else if (y_prev - y <= 1) return y;
        }
        require(false, "Price: Convergence false");
    }

    function getD(uint256[2] memory xp, uint256 a)
        internal
        pure
        returns (uint256 D)
    {
        // Solution is taken from pool contract: 0xc9C32cd16Bf7eFB85Ff14e0c8603cc90F6F2eE49
        uint256 S;
        uint256 Dprev;
        for (uint256 _i; _i < xp.length; ++_i) {
            S += xp[_i];
        }
        if (S == 0) return 0;

        D = S;
        uint256 Ann = a * N_COINS;
        for (uint256 _i; _i < 256; ++_i) {
            uint256 D_P = D;
            for (uint256 _j; _j < xp.length; ++_j) {
                D_P = (D_P * D) / (xp[_j] * N_COINS);
            }
            Dprev = D;
            D =
                (((Ann * S) / A_PRECISION + D_P * N_COINS) * D) /
                (((Ann - A_PRECISION) * D) / A_PRECISION + (N_COINS + 1) * D_P);
            if (D > Dprev && D - Dprev <= 1) return D;
            else if (Dprev - D <= 1) return D;
        }
        require(false, "Price: Convergence false");
        return 0;
    }

    function getYD(
        uint256 a,
        uint256 i_,
        uint256[2] memory xp,
        uint256 D
    ) internal pure returns (uint256 y) {
        // Solution is taken from pool contract: 0xc9C32cd16Bf7eFB85Ff14e0c8603cc90F6F2eE49
        uint256 S_ = 0;
        uint256 _x = 0;
        uint256 y_prev = 0;
        uint256 c = D;
        uint256 Ann = a * N_COINS;

        for (uint256 _i; _i < N_COINS; ++_i) {
            if (_i != i_) _x = xp[_i];
            else continue;
            S_ += _x;
            c = (c * D) / (_x * N_COINS);
        }

        c = (c * D * A_PRECISION) / (Ann * N_COINS);
        uint256 b = S_ + (D * A_PRECISION) / Ann; // - D
        y = D;

        for (uint256 _i; _i < 255; ++_i) {
            y_prev = y;
            y = (y * y + c) / (2 * y + b - D);
            if (y > y_prev && y - y_prev <= 1) return y;
            else if (y_prev - y <= 1) return y;
        }
        require(false, "Price: Convergence false");
    }

    /**
     * @dev Return the `xp` array for two tokens. Adjusts `balances[0]` by `padding`
     * and `balances[1]` by `rate / PRECISION`.
     * 
     * This is provided as a gas optimization when `rates[0] * PRECISION` has been
     * pre-computed.
     */
    function getXP(
        uint256[2] memory balances,
        uint256 padding,
        uint256 rate
    ) internal pure returns (uint256[2] memory xp) {
        xp[0] = balances[0].mul(padding);
        xp[1] = balances[1].mul(rate).div(PRECISION);
    }

    /**
     * @dev Return the `xp` array for two tokens. Adjusts `balances[0]` by `rates[0]`
     * and `balances[1]` by `rates[1] / PRECISION`.
     */
    function getXP(
        uint256[2] memory balances,
        uint256[2] memory rates
    ) internal pure returns (uint256[2] memory xp) {
        xp[0] = balances[0].mul(rates[0]).div(PRECISION);
        xp[1] = balances[1].mul(rates[1]).div(PRECISION);
    }
}

File 38 of 54 : LibMetaCurve.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

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

/**
 * @dev Curve Metapool extended interface.
 */
interface IMeta3Curve {
    function A_precise() external view returns (uint256);
    function get_previous_balances() external view returns (uint256[2] memory);
    function get_virtual_price() external view returns (uint256);
}

/**
 * @title LibMetaCurve
 * @author Publius
 * @notice Wraps {LibCurve} with metadata about Curve Metapools, including the
 * `A` parameter and virtual price.
 */
library LibMetaCurve {
    using SafeMath for uint256;
    
    /**
     * @dev Used in {LibBeanMetaCurve}.
     */
    function getXP(
        uint256[2] memory balances,
        uint256 padding
    ) internal view returns (uint256[2] memory) {
        return LibCurve.getXP(
            balances,
            padding,
            C.curve3Pool().get_virtual_price()
        );
    }

    /**
     * @dev Used in {LibBeanMetaCurve}.
     */
    function getDFroms(
        address pool,
        uint256[2] memory balances,
        uint256 padding
    ) internal view returns (uint256) {
        return LibCurve.getD(
            getXP(balances, padding),
            IMeta3Curve(pool).A_precise()
        );
    }
}

File 39 of 54 : 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 40 of 54 : 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 41 of 54 : 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 42 of 54 : LibPRBMath.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;


/**
 * @title LibPRBMath contains functionality to compute powers of 60.18 unsigned floating point to uint256
 * Solution taken from https://github.com/paulrberg/prb-math/blob/main/contracts/PRBMathUD60x18.sol
 * and adapted to Solidity 0.7.6
**/
library LibPRBMath {

    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    // /// @dev How many trailing decimals can be represented.
    //uint256 internal constant SCALE = 1e18;

    // /// @dev Largest power of two divisor of SCALE.
    // uint256 internal constant SCALE_LPOTD = 262144;

    // /// @dev SCALE inverted mod 2^256.
    // uint256 internal constant SCALE_INVERSE =
    //     78156646155174841979727994598816262306175212592076161876661_508869554232690281;


    /// @dev How many trailing decimals can be represented.
    uint256 internal constant SCALE = 1e18;

     /// @dev Half the SCALE number.
    uint256 internal constant HALF_SCALE = 5e17;

    /// @dev Largest power of two divisor of SCALE.
    uint256 internal constant SCALE_LPOTD = 68719476736;

    /// @dev SCALE inverted mod 2^256.
    uint256 internal constant SCALE_INVERSE =
        24147664466589061293728112707504694672000531928996266765558539143717230155537;

    function powu(uint256 x, uint256 y) internal pure returns (uint256 result) {
        // Calculate the first iteration of the loop in advance.
        result = y & 1 > 0 ? x : SCALE;

        // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster.
        for (y >>= 1; y > 0; y >>= 1) {
            x = mulDivFixedPoint(x, x);

            // Equivalent to "y % 2 == 1" but faster.
            if (y & 1 > 0) {
                result = mulDivFixedPoint(result, x);
            }
        }
    }

    function mulDivFixedPoint(uint256 x, uint256 y) internal pure returns (uint256 result) {
        uint256 prod0;
        uint256 prod1;
        assembly {
            let mm := mulmod(x, y, not(0))
            prod0 := mul(x, y)
            prod1 := sub(sub(mm, prod0), lt(mm, prod0))
        }

        if (prod1 >= SCALE) {
            revert("fixed point overflow");
        }

        uint256 remainder;
        uint256 roundUpUnit;
        assembly {
            remainder := mulmod(x, y, SCALE)
            roundUpUnit := gt(remainder, 499999999999999999)
        }

        if (prod1 == 0) {
            result = (prod0 / SCALE) + roundUpUnit;
            return result;
        }

        assembly {
            result := add(
                mul(
                    or(
                        div(sub(prod0, remainder), SCALE_LPOTD),
                        mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, SCALE_LPOTD), SCALE_LPOTD), 1))
                    ),
                    SCALE_INVERSE
                ),
                roundUpUnit
            )
        }
    }

    function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) {
        if (x >= 2**128) {
            x >>= 128;
            msb += 128;
        }
        if (x >= 2**64) {
            x >>= 64;
            msb += 64;
        }
        if (x >= 2**32) {
            x >>= 32;
            msb += 32;
        }
        if (x >= 2**16) {
            x >>= 16;
            msb += 16;
        }
        if (x >= 2**8) {
            x >>= 8;
            msb += 8;
        }
        if (x >= 2**4) {
            x >>= 4;
            msb += 4;
        }
        if (x >= 2**2) {
            x >>= 2;
            msb += 2;
        }
        if (x >= 2**1) {
            // No need to shift x any more.
            msb += 1;
        }
    }

    function logBase2(uint256 x) internal pure returns (uint256 result) {
        if (x < SCALE) {
            revert("Log Input Too Small");
        }
        // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n).
        uint256 n = mostSignificantBit(x / SCALE);

        // The integer part of the logarithm as an unsigned 60.18-decimal fixed-point number. The operation can't overflow
        // because n is maximum 255 and SCALE is 1e18.
        result = n * SCALE;

        // This is y = x * 2^(-n).
        uint256 y = x >> n;

        // If y = 1, the fractional part is zero.
        if (y == SCALE) {
            return result;
        }

        // Calculate the fractional part via the iterative approximation.
        // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster.
        for (uint256 delta = HALF_SCALE; delta > 0; delta >>= 1) {
            y = (y * y) / SCALE;

            // Is y^2 > 2 and so in the range [2,4)?
            if (y >= 2 * SCALE) {
                // Add the 2^(-m) factor to the logarithm.
                result += delta;

                // Corresponds to z/2 on Wikipedia.
                y >>= 1;
            }
        }
    }

    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a >= b ? a : b;
    }

    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a <= b ? a : b;
    }

    function min(uint128 a, uint128 b) internal pure returns (uint256) {
        return a <= b ? a : b;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }
}

File 43 of 54 : 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 44 of 54 : 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 45 of 54 : 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 46 of 54 : 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 47 of 54 : LibUnripe.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IBean} from "../interfaces/IBean.sol";
import {AppStorage, LibAppStorage} from "./LibAppStorage.sol";
import {C} from "../C.sol";

/**
 * @title LibUnripe
 * @author Publius
 */
library LibUnripe {
    using SafeMath for uint256;

    event ChangeUnderlying(address indexed token, int256 underlying);
    event SwitchUnderlyingToken(address indexed token, address indexed underlyingToken);

    uint256 constant DECIMALS = 1e6;

    function percentBeansRecapped() internal view returns (uint256 percent) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        return
            s.u[C.UNRIPE_BEAN].balanceOfUnderlying.mul(DECIMALS).div(
                C.unripeBean().totalSupply()
            );
    }

    function percentLPRecapped() internal view returns (uint256 percent) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        return
            C.unripeLPPerDollar().mul(s.recapitalized).div(
                C.unripeLP().totalSupply()
            );
    }

    function incrementUnderlying(address token, uint256 amount) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        s.u[token].balanceOfUnderlying = s.u[token].balanceOfUnderlying.add(
            amount
        );
        emit ChangeUnderlying(token, int256(amount));
    }

    function decrementUnderlying(address token, uint256 amount) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        s.u[token].balanceOfUnderlying = s.u[token].balanceOfUnderlying.sub(
            amount
        );
        emit ChangeUnderlying(token, -int256(amount));
    }

    function unripeToUnderlying(address unripeToken, uint256 unripe)
        internal
        view
        returns (uint256 underlying)
    {
        AppStorage storage s = LibAppStorage.diamondStorage();
        underlying = s.u[unripeToken].balanceOfUnderlying.mul(unripe).div(
            IBean(unripeToken).totalSupply()
        );
    }

    function underlyingToUnripe(address unripeToken, uint256 underlying)
        internal
        view
        returns (uint256 unripe)
    {
        AppStorage storage s = LibAppStorage.diamondStorage();
        unripe = IBean(unripeToken).totalSupply().mul(underlying).div(
            s.u[unripeToken].balanceOfUnderlying
        );
    }

    function addUnderlying(address token, uint256 underlying) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        if (token == C.UNRIPE_LP) {
            uint256 recapped = underlying.mul(s.recapitalized).div(
                s.u[C.UNRIPE_LP].balanceOfUnderlying
            );
            s.recapitalized = s.recapitalized.add(recapped);
        }
        incrementUnderlying(token, underlying);
    }

    function removeUnderlying(address token, uint256 underlying) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        if (token == C.UNRIPE_LP) {
            uint256 recapped = underlying.mul(s.recapitalized).div(
                s.u[C.UNRIPE_LP].balanceOfUnderlying
            );
            s.recapitalized = s.recapitalized.sub(recapped);
        }
        decrementUnderlying(token, underlying);
    }

    /**
     * @dev Switches the underlying token of an unripe token.
     * Should only be called if `s.u[unripeToken].balanceOfUnderlying == 0`.
     */
    function switchUnderlyingToken(address unripeToken, address newUnderlyingToken) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        s.u[unripeToken].underlyingToken = newUnderlyingToken;
        emit SwitchUnderlyingToken(unripeToken, newUnderlyingToken);
    }
}

File 48 of 54 : LibChainlinkOracle.sol
/**
 * SPDX-License-Identifier: MIT
 **/

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import {C} from "contracts/C.sol";
import {IChainlinkAggregator} from "contracts/interfaces/chainlink/IChainlinkAggregator.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";

/**
 * @title Chainlink Oracle Library
 * @notice Contains functionalty to fetch prices from Chainlink price feeds.
 * @dev currently supports:
 * - ETH/USD price feed
 **/
library LibChainlinkOracle {

    using SafeMath for uint256;

    // Uses the same timeout as Liquity's Chainlink timeout.
    uint256 constant public CHAINLINK_TIMEOUT = 14400;  // 4 hours: 60 * 60 * 4

    IChainlinkAggregator constant priceAggregator = IChainlinkAggregator(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
    uint256 constant PRECISION = 1e6; // use 6 decimal precision.

    /**
     * @dev Returns the most recently reported ETH/USD price from the Chainlink Oracle.
     * Return value has 6 decimal precision.
     * Returns 0 if Chainlink's price feed is broken or frozen.
    **/
    function getEthUsdPrice() internal view returns (uint256 price) {
        // First, try to get current decimal precision:
        uint8 decimals;
        try priceAggregator.decimals() returns (uint8 _decimals) {
            // If call to Chainlink succeeds, record the current decimal precision
            decimals = _decimals;
        } catch {
            // If call to Chainlink aggregator reverts, return a price of 0 indicating failure
            return 0;
        }

        // Secondly, try to get latest price data:
        try priceAggregator.latestRoundData() returns
        (
            uint80 roundId,
            int256 answer,
            uint256 /* startedAt */,
            uint256 timestamp,
            uint80 /* answeredInRound */
        )
        {
            // Check for an invalid roundId that is 0
            if (roundId == 0) return 0;
            // Check for an invalid timeStamp that is 0, or in the future
            if (timestamp == 0 || timestamp > block.timestamp) return 0;
            // Check if Chainlink's price feed has timed out
            if (block.timestamp.sub(timestamp) > CHAINLINK_TIMEOUT) return 0;
            // Check for non-positive price
            if (answer <= 0) return 0;
            // Return the 
            return uint256(answer).mul(PRECISION).div(10**decimals);
        } catch {
            // If call to Chainlink aggregator reverts, return a price of 0 indicating failure
            return 0;
        }
    }
}

File 49 of 54 : LibEthUsdOracle.sol
/**
 * SPDX-License-Identifier: MIT
 **/

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

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

/**
 * @title Eth Usd Oracle Library
 * @notice Contains functionalty to fetch a manipulation resistant ETH/USD price.
 * @dev
 * The Oracle uses a greedy approach to return the average price between the
 * current price returned ETH/USD Chainlink Oracle and either the ETH/USDC
 * Uniswap V3 0.05% fee pool and the ETH/USDT Uniswap V3 0.05% fee pool depending
 * on which is closer. 
 * 
 * If the prices in the ETH/USDC Uniswap V3 0.05% fee pool and USD/USDT Uniswap V3 0.05% fee pool are
 * greater than `MAX_DIFFERENCE` apart, then the oracle uses the Chainlink price to maximize liveness.
 * 
 * The approach is greedy as if the ETH/USDC Uniswap price is sufficiently close
 * to the Chainlink Oracle price (See {MAX_GREEDY_DIFFERENCE}), then the Oracle
 * will not check the ETH/USDT Uniswap Price to save gas.
 * 
 * The oracle will fail if the Chainlink Oracle is broken or frozen (See: {LibChainlinkOracle}).
 **/
library LibEthUsdOracle {

    using SafeMath for uint256;

    // The maximum percent different such that it is acceptable to use the greedy approach.
    uint256 constant MAX_GREEDY_DIFFERENCE = 0.003e18; // 0.3%

    // The maximum percent difference such that the oracle assumes no manipulation is occuring.
    uint256 constant MAX_DIFFERENCE = 0.01e18; // 1%
    uint256 constant ONE = 1e18;

    /**
     * @dev Returns the ETH/USD price.
     * Return value has 6 decimal precision.
     * Returns 0 if the Eth Usd Oracle cannot fetch a manipulation resistant price.
    **/
    function getEthUsdPrice() internal view returns (uint256) {

        uint256 chainlinkPrice = LibChainlinkOracle.getEthUsdPrice();
        // Check if the chainlink price is broken or frozen.
        if (chainlinkPrice == 0) return 0;

        uint256 usdcPrice = LibUniswapOracle.getEthUsdcPrice();
        uint256 usdcChainlinkPercentDiff = getPercentDifference(usdcPrice, chainlinkPrice);

        // Check if the USDC price and the Chainlink Price are sufficiently close enough
        // to warrant using the greedy approach.
        if (usdcChainlinkPercentDiff < MAX_GREEDY_DIFFERENCE) {
            return chainlinkPrice.add(usdcPrice).div(2);
        }

        uint256 usdtPrice = LibUniswapOracle.getEthUsdtPrice();
        uint256 usdtChainlinkPercentDiff = getPercentDifference(usdtPrice, chainlinkPrice);

        // Check whether the USDT or USDC price is closer to the Chainlink price.
        if (usdtChainlinkPercentDiff < usdcChainlinkPercentDiff) {
            // Check whether the USDT price is too far from the Chainlink price.
            if (usdtChainlinkPercentDiff < MAX_DIFFERENCE) {
                return chainlinkPrice.add(usdtPrice).div(2);
            }
            return chainlinkPrice;
        } else {
            // Check whether the USDC price is too far from the Chainlink price.
            if (usdcChainlinkPercentDiff < MAX_DIFFERENCE) {
                return chainlinkPrice.add(usdcPrice).div(2);
            }
            return chainlinkPrice;
        }
    }

    /**
     * Gets the percent difference between two values with 18 decimal precision.
     * @dev If x == 0 (Such as in the case of Uniswap Oracle failure), then the percent difference is calculated as 100%.
     */
    function getPercentDifference(uint x, uint y) internal pure returns (uint256 percentDifference) {
        percentDifference = x.mul(ONE).div(y);
        percentDifference = x > y ?
            percentDifference - ONE :
            ONE - percentDifference; // SafeMath unnecessary due to conditional check
    }
}

File 50 of 54 : LibUniswapOracle.sol
/**
 * SPDX-License-Identifier: MIT
 **/

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import {C} from "contracts/C.sol";
import {OracleLibrary} from "@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol";
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';

/**
 * @title Uniswap Oracle Library
 * @notice Contains functionalty to read prices from Uniswap V3 pools.
 * @dev currently supports:
 * - ETH:USDC price from the ETH:USDC 0.05% pool
 * - ETH:USDT price from the ETH:USDT 0.05% pool
 **/
library LibUniswapOracle {

    // The lookback in seconds for which to calculate the SMA in a Uniswap V3 pool.
    // Set to 15 minutes
    uint32 constant PERIOD = 900;

    uint128 constant ONE_WETH = 1e18;

    /**
     * @dev Uses the Uniswap V3 Oracle to get the price of ETH denominated in USDC.
     * Return value has 6 decimal precision.
     * Returns 0 if {IUniswapV3Pool.observe} reverts.
     */
    function getEthUsdcPrice() internal view returns (uint256 price) {
        (bool success, int24 tick) = consult(C.UNIV3_ETH_USDC_POOL, PERIOD);
        if (!success) return 0;
        price = OracleLibrary.getQuoteAtTick(tick, ONE_WETH, C.WETH, C.USDC);
    }

    /**
     * @dev Uses the Uniswap V3 Oracle to get the price of ETH denominated in USDT.
     * Return value has 6 decimal precision.
     * Returns 0 if {IUniswapV3Pool.observe} reverts.
     */
    function getEthUsdtPrice() internal view returns (uint256 price) {
        (bool success, int24 tick) = consult(C.UNIV3_ETH_USDT_POOL, PERIOD);
        if (!success) return 0;
        price = OracleLibrary.getQuoteAtTick(tick, ONE_WETH, C.WETH, C.USDT);
    }

    /**
     * @dev A variation of {OracleLibrary.consult} that returns just the arithmetic mean tick and returns 0 on failure
     * instead of reverting if {IUniswapV3Pool.observe} reverts.
     * https://github.com/Uniswap/v3-periphery/blob/51f8871aaef2263c8e8bbf4f3410880b6162cdea/contracts/libraries/OracleLibrary.sol
     */
    function consult(address pool, uint32 secondsAgo)
        internal
        view
        returns (bool success, int24 arithmeticMeanTick)
    {
        require(secondsAgo != 0, 'BP');

        uint32[] memory secondsAgos = new uint32[](2);
        secondsAgos[0] = secondsAgo;
        secondsAgos[1] = 0;

        try IUniswapV3Pool(pool).observe(secondsAgos) returns (
            int56[] memory tickCumulatives,
            uint160[] memory
        ) {
            int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
            arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgo);
            // Always round to negative infinity
            if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgo != 0)) arithmeticMeanTick--;
            success = true;
        } catch {}
    }

}

File 51 of 54 : LibUsdOracle.sol
/**
 * SPDX-License-Identifier: MIT
 **/

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

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

/**
 * @title Eth Usd Oracle Library
 * @notice Contains functionalty to fetch the manipulation resistant USD price of different tokens.
 * @dev currently supports:
 * - ETH/USD price
 **/
library LibUsdOracle {

    using SafeMath for uint256;

    /**
     * @dev Returns the price of a given token in in USD.
     */
    function getUsdPrice(address token) internal view returns (uint256) {
        if (token == C.WETH) {
            uint256 ethUsdPrice = LibEthUsdOracle.getEthUsdPrice();
            if (ethUsdPrice == 0) return 0;
            return uint256(1e24).div(ethUsdPrice);
        }
        revert("Oracle: Token not supported.");
    }

}

File 52 of 54 : 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 {LibPRBMath} from "../LibPRBMath.sol";
import {LibTokenSilo} from "./LibTokenSilo.sol";
import {LibSafeMath128} from "../LibSafeMath128.sol";
import {LibSafeMathSigned96} from "../LibSafeMathSigned96.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 LibPRBMath for uint256;
    using SafeCast for uint256;
    
    // The `VESTING_PERIOD` is the number of blocks that must pass before
    // a farmer is credited with their earned beans issued that season. 
    uint256 internal constant VESTING_PERIOD = 10;

    //////////////////////// 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
    );

    struct AssetsRemoved {
        uint256 tokensRemoved;
        uint256 stalkRemoved;
        uint256 bdvRemoved;
    }

    /**
     * @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
     */
    function mintStalk(address account, uint256 stalk) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();

        // Calculate the amount of Roots for the given amount of Stalk.
        uint256 roots;
        if (s.s.roots == 0) {
            roots = uint256(stalk.mul(C.getRootsBase()));
        } else {
            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));
    }


    /**
     * @dev mints grownStalk to `account`.
     * 
     * per the zero-withdraw update, if a user plants during the vesting period (see constant),
     * the earned beans of the current season is deferred until the non vesting period.
     * However, this causes a slight mismatch in the amount of roots to properly allocate to the user.
     * 
     * The formula for calculating the roots is:
     * GainedRoots = TotalRoots * GainedStalk / TotalStalk.
     * 
     * Roots are utilized in {SiloExit.balanceOfEarnedBeans} to calculate the earned beans as such: 
     * EarnedBeans = (TotalStalk * userRoots / TotalRoots) - userStalk  
     * 
     * Because TotalStalk increments when there are new beans issued (at sunrise), 
     * the amount of roots issued without the earned beans are:
     * GainedRoots = TotalRoots * GainedStalk / (TotalStalk - NewEarnedStalk)
     * 
     * since newEarnedStalk is always equal or greater than 0, the gained roots calculated without the earned beans
     * will always be equal or larger than the gained roots calculated with the earned beans.
     * 
     * @param account the address to mint Stalk and Roots to
     * @param stalk the amount of stalk to mint
     */
    function mintGrownStalk(address account, uint256 stalk) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();

        uint256 roots;
        if (s.s.roots == 0) {
            roots = stalk.mul(C.getRootsBase());
        } else {
            roots = s.s.roots.mul(stalk).div(s.s.stalk);
            if (inVestingPeriod()) {
                // Safe Math is unnecessary for because total Stalk > new Earned Stalk
                uint256 rootsWithoutEarned = s.s.roots.add(s.vestingPeriodRoots).mul(stalk).div(s.s.stalk - s.newEarnedStalk);
                // Safe Math is unnecessary for because rootsWithoutEarned >= roots
                uint128 deltaRoots = (rootsWithoutEarned - roots).toUint128();
                s.vestingPeriodRoots = s.vestingPeriodRoots.add(deltaRoots);
                s.a[account].deltaRoots = deltaRoots;
            }
        }

        // 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));
    }

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

    /**
     * @dev Burns Stalk and Roots from `account`.
     *
     * if the user withdraws in the vesting period, 
     * they forfeit their earned beans for that season, 
     * distrubuted to the other users.
     */
    function burnStalk(address account, uint256 stalk) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        if (stalk == 0) return;
       
        uint256 roots;
        // Calculate the amount of Roots for the given amount of Stalk.
        // We round up as it prevents an account having roots but no stalk.
        
        // if the user withdraws in the vesting period, they forfeit their earned beans for that season
        // this is distributed to the other users.
        if(inVestingPeriod()){
            roots = s.s.roots.mulDiv(
                stalk,
                s.s.stalk-s.newEarnedStalk,
                LibPRBMath.Rounding.Up
            );
            // cast to uint256 to prevent overflow
            uint256 deltaRootsRemoved = uint256(s.a[account].deltaRoots)
                .mul(stalk)
                .div(s.a[account].s.stalk);
            s.a[account].deltaRoots = s.a[account].deltaRoots.sub(deltaRootsRemoved.toUint128());
        } else {
            roots = s.s.roots.mulDiv(
            stalk,
            s.s.stalk,
            LibPRBMath.Rounding.Up);
        }

        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);
        
        // Oversaturated was previously referred to as Raining and thus
        // code references mentioning Rain really refer to Oversaturation
        // If Beanstalk is Oversaturated, subtract Roots from both the
        // account's and Beanstalk's Oversaturated Roots balances.
        // For more info on Oversaturation, See {Weather.handleRain}
        if (s.season.raining) {
            s.r.roots = s.r.roots.sub(roots);
            s.a[account].sop.roots = s.a[account].roots;
        }

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

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

    /**
     * @notice Decrements the Stalk and Roots of `sender` and increments the Stalk
     * and Roots of `recipient` by the same amount.
     * 
     * If the transfer is done during the vesting period, the earned beans are still
     * defered until after the vesting period has elapsed. 
     * @dev There may be cases where more than the earned beans 
     * of the current season is vested, but can be claimed after the v.e has ended.
     * We accept this inefficency due to 
     * 1) the short vesting period.
     * 2) math complexity/gas costs needed to implement a correct solution.
     * 3) security risks.
     */
    function transferStalk(
        address sender,
        address recipient,
        uint256 stalk
    ) internal {
        AppStorage storage s = LibAppStorage.diamondStorage();
        uint256 roots;
        if(inVestingPeriod()){
            // transferring all stalk means that the earned beans is transferred.
            // deltaRoots cannot be transferred as it is calculated on an account basis. 
            if(stalk == s.a[sender].s.stalk){
                s.a[sender].deltaRoots = 0;
            } else {
                // partial transfer
                uint256 deltaRootsRemoved = uint256(s.a[sender].deltaRoots)
                    .mul(stalk)
                    .div(s.a[sender].s.stalk);
                s.a[sender].deltaRoots = s.a[sender].deltaRoots.sub(deltaRootsRemoved.toUint128());
            }
            roots = stalk == s.a[sender].s.stalk
                ? s.a[sender].roots
                : s.s.roots.sub(1).mul(stalk).div(s.s.stalk - s.newEarnedStalk).add(1);
        } else {
            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));

        // 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));
    }

    /**
     * @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 {

        require(!migrationNeeded(account), "Silo: Migration needed");

        AppStorage storage s = LibAppStorage.diamondStorage();
        //sop stuff 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) {
            uint32 lastUpdate = _lastUpdate(account);
            if (lastUpdate <= s.season.rainStart && lastUpdate <= s.season.current) {
                // Increments `plenty` for `account` if a Flood has occured.
                // Saves Rain Roots for `account` if it is Raining.
                handleRainAndSops(account, lastUpdate);

                // Reset timer so that Grown Stalk for a particular Season can only be 
                // claimed one time. 
                s.a[account].lastUpdate = s.season.current;
            }
        }
        
        // Calculate the amount of Grown Stalk claimable by `account`.
        // Increase the account's balance of Stalk and Roots.
        __mow(account, token);

        // was hoping to not have to update lastUpdate, but if you don't, then it's 0 for new depositors, this messes up mow and migrate in unit tests, maybe better to just set this manually for tests?
        // anyone that would have done any deposit has to go through mowSender which would have init'd it above zero in the pre-migration days
        s.a[account].lastUpdate = s.season.current;
    }

    /**
     * @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;
            }

            mintGrownStalk(
                account,
                _balanceOfGrownStalk(
                    _lastStem,
                    _stemTip,
                    _bdv
                )
            );
        }

        // If this `account` has no BDV, skip to save gas. Still need to 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) private {
        AppStorage storage s = LibAppStorage.diamondStorage();
        // 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 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 (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 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 stalkRemoved,
            uint256 bdvRemoved
        )
    {
        AppStorage storage s = LibAppStorage.diamondStorage();

        bdvRemoved = LibTokenSilo.removeDepositFromAccount(account, token, stem, amount);

        //need to get amount of stalk earned by this deposit (index of now minus index of when deposited)
        stalkRemoved = bdvRemoved.mul(s.ss[token].stalkIssuedPerBdv).add(
            stalkReward(
                stem, //this is the index of when it was deposited
                LibTokenSilo.stemTipForToken(token), //this is latest for this token
                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}
     */
    function _removeDepositsFromAccount(
        address account,
        address token,
        int96[] calldata stems,
        uint256[] calldata amounts
    ) internal returns (AssetsRemoved memory ar) {
        AppStorage storage s = LibAppStorage.diamondStorage();

        //make bdv array and add here?
        uint256[] memory bdvsRemoved = new uint256[](stems.length);
        uint256[] memory removedDepositIDs = new uint256[](stems.length);

        for (uint256 i; i < stems.length; ++i) {
            uint256 crateBdv = LibTokenSilo.removeDepositFromAccount(
                account,
                token,
                stems[i],
                amounts[i]
            );
            bdvsRemoved[i] = crateBdv;
            removedDepositIDs[i] = LibBytes.packAddressAndStem(token, stems[i]);
            ar.bdvRemoved = ar.bdvRemoved.add(crateBdv);
            ar.tokensRemoved = ar.tokensRemoved.add(amounts[i]);

            ar.stalkRemoved = ar.stalkRemoved.add(
                stalkReward(
                    stems[i],
                    LibTokenSilo.stemTipForToken(token),
                    crateBdv.toUint128()
                )
            );

        }

        ar.stalkRemoved = ar.stalkRemoved.add(
            ar.bdvRemoved.mul(s.ss[token].stalkIssuedPerBdv)
        );

        // "removing" deposits is equivalent to "burning" a batch of ERC1155 tokens.
        emit TransferBatch(msg.sender, account, address(0), removedDepositIDs, amounts);
        emit RemoveDeposits(account, token, stems, amounts, ar.tokensRemoved, bdvsRemoved);
    }

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

    /**
     * @dev 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)
     */
    function stalkReward(int96 startStem, int96 endStem, uint128 bdv) //are the types what we want here?
        internal
        pure
        returns (uint256)
    {
        int96 reward = endStem.sub(startStem).mul(int96(bdv));
        
        return uint128(reward);
    }

    /**
     * @dev check whether beanstalk is in the vesting period.
     */
    function inVestingPeriod() internal view returns (bool) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        return block.number - s.season.sunriseBlock <= VESTING_PERIOD;
    }

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

File 53 of 54 : 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.sol";
import "../../C.sol";
import "contracts/libraries/LibSafeMath32.sol";
import "contracts/libraries/LibSafeMath128.sol";
import "contracts/libraries/LibSafeMathSigned128.sol";
import "contracts/libraries/LibSafeMathSigned96.sol";
import "contracts/libraries/LibBytes.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;


    //////////////////////// 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
    );

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


    //////////////////////// ACCOUNTING: TOTALS ////////////////////////
    
    /**
     * @dev Increment the total amount and bdv of `token` deposited in the Silo.
     */
    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()
        );
    }

    /**
     * @dev Decrement the total amount and bdv of `token` deposited in the Silo.
     */
    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()
        );
    }

    /**
     * @dev 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) {
        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) {
        require(bdv > 0, "Silo: No Beans under Token.");
        AppStorage storage s = LibAppStorage.diamondStorage();
        
        incrementTotalDeposited(token, amount, bdv);
        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 to the deposits, and update the deposit.
        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());
        
        // update the mow status (note: mow status is per token, not per depositId)
        // SafeMath not necessary as the bdv is already checked to be <= type(uint128).max
        s.a[account].mowStatuses[token].bdv = uint128(s.a[account].mowStatuses[token].bdv.add(uint128(bdv)));

        /** 
         *  {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
                uint256(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;

        require(amount <= crateAmount, "Silo: Crate balance too low.");

        // Partial remove
        if (amount < crateAmount) {
            uint256 removedBDV = amount.mul(crateBDV).div(crateAmount);
            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 = uint128(updatedAmount);
            s.a[account].deposits[depositId].bdv = uint128(updatedBDV);
            //remove from the mow status bdv amount, which keeps track of total token deposited per farmer
            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(
            uint128(crateBDV)
        );
    }

    //////////////////////// 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. Formerly just seeds.
     * Note this is stored as 1e6, i.e. 1_000_000 units of this is equal to 1 old seed.
     */
    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 _stemTipForToken)
    {
        AppStorage storage s = LibAppStorage.diamondStorage();
        
        // SafeCast unnecessary because all casted variables are types smaller that int96.
        _stemTipForToken = s.ss[token].milestoneStem +
        int96(s.ss[token].stalkEarnedPerSeason).mul(
            int96(s.season.current).sub(int96(s.ss[token].milestoneSeason))
        ).div(1e6); //round here 
    }

    /**
     * @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));
        (, uint bdv) = getDeposit(account, token, stem);

        grownStalk = deltaStemTip.mul(bdv);
    }

    /**
     * @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));
    }

    /**
     * @dev returns the stem of a deposit, based on the amount of grown stalk it has earned.
     */
    function calculateGrownStalkAndStem(address token, uint256 grownStalk, uint256 bdv)
        internal
        view 
        returns (uint256 _grownStalk, int96 stem)
    {
        int96 _stemTipForToken = stemTipForToken(token);
        stem = _stemTipForToken.sub(toInt96(grownStalk.div(bdv)));
        _grownStalk = uint256(_stemTipForToken.sub(stem).mul(toInt96(bdv)));
    }


    /**
     * @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.div(bdv)) : 0;

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

    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 54 of 54 : LibWell.sol
/*
 SPDX-License-Identifier: MIT
*/

pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;

import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IInstantaneousPump} from "contracts/interfaces/basin/pumps/IInstantaneousPump.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Call, IWell} from "contracts/interfaces/basin/IWell.sol";
import {IWellFunction} from "contracts/interfaces/basin/IWellFunction.sol";
import {C} from "contracts/C.sol";
import {AppStorage, LibAppStorage} from "../LibAppStorage.sol";
import {LibUsdOracle} from "contracts/libraries/Oracle/LibUsdOracle.sol";

/**
 * @title Well Library
 * Contains helper functions for common Well related functionality.
 **/
library LibWell {

    using SafeMath for uint256;

    /**
     * @dev Returns the price ratios between `tokens` and the index of Bean in `tokens`.
     * These actions are combined into a single function for gas efficiency.
     */
    function getRatiosAndBeanIndex(IERC20[] memory tokens) internal view returns (
        uint[] memory ratios,
        uint beanIndex,
        bool success
    ) {
        success = true;
        ratios = new uint[](tokens.length);
        beanIndex = type(uint256).max;
        for (uint i; i < tokens.length; ++i) {
            if (C.BEAN == address(tokens[i])) {
                beanIndex = i;
                ratios[i] = 1e6;
            } else {
                ratios[i] = LibUsdOracle.getUsdPrice(address(tokens[i]));
                if (ratios[i] == 0) {
                    success = false;
                }
            }
        }
        require(beanIndex != type(uint256).max, "Bean not in Well.");
    }
    
    /**
     * @dev Returns the index of Bean in a list of tokens.
     */
    function getBeanIndex(IERC20[] memory tokens) internal pure returns (uint beanIndex) {
        for (beanIndex; beanIndex < tokens.length; ++beanIndex) {
            if (C.BEAN == address(tokens[beanIndex])) {
                return beanIndex;
            }
        }
        revert("Bean not in Well.");
    }

    /**
     * @dev Returns the index of Bean given a Well.
     */
    function getBeanIndexFromWell(address well) internal view returns (uint beanIndex) {
        IERC20[] memory tokens = IWell(well).tokens();
        beanIndex = getBeanIndex(tokens);
    }

    /**
     * @dev Returns whether an address is a whitelisted Well by checking
     * if the BDV function selector is the `wellBdv` function.
     */
    function isWell(
        address well
    ) internal view returns (bool _isWell) {
        AppStorage storage s = LibAppStorage.diamondStorage();
        return s.ss[well].selector == 0xc84c7727;
    }
}

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

Contract Security Audit

Contract ABI

API
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"address","name":"fromToken","type":"address"},{"indexed":false,"internalType":"address","name":"toToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"fromAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"toAmount","type":"uint256"}],"name":"Convert","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"int96","name":"stem","type":"int96"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"bdv","type":"uint256"}],"name":"RemoveDeposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"int96[]","name":"stems","type":"int96[]"},{"indexed":false,"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256[]","name":"bdvs","type":"uint256[]"}],"name":"RemoveDeposits","type":"event"},{"inputs":[{"internalType":"bytes","name":"convertData","type":"bytes"},{"internalType":"int96[]","name":"stems","type":"int96[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"name":"convert","outputs":[{"internalType":"int96","name":"toStem","type":"int96"},{"internalType":"uint256","name":"fromAmount","type":"uint256"},{"internalType":"uint256","name":"toAmount","type":"uint256"},{"internalType":"uint256","name":"fromBdv","type":"uint256"},{"internalType":"uint256","name":"toBdv","type":"uint256"}],"stateMutability":"payable","type":"function"}]

608060405234801561001057600080fd5b50615eba80620000216000396000f3fe60806040526004361061001e5760003560e01c8063b362a6e814610023575b600080fd5b610036610031366004615313565b610050565b604051610047959493929190615861565b60405180910390f35b600080600080600060026000601e015414156100875760405162461bcd60e51b815260040161007e90615c23565b60405180910390fd5b6002601e556000808061009a8c8c610153565b9950975090935091506100ad3383610412565b6100b73384610412565b6100c3828b8b8a610555565b9550905060006100d3848861092e565b90508581116100e257856100e4565b805b94506100f284888785610a61565b9850336001600160a01b03167f3f7117900f070f33613da64255c3e8a5b791ff071197653712e53fde9c3dab3d84868b8b6040516101339493929190615677565b60405180910390a250506001601e55509499939850919650945092509050565b600080600080600061019a87878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610ae692505050565b905060008160068111156101aa57fe5b14156101fe576101ef87878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610b0492505050565b92975090955093509150610408565b600181600681111561020c57fe5b1415610251576101ef87878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610b4f92505050565b600281600681111561025f57fe5b14156102a4576101ef87878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610b9992505050565b60038160068111156102b257fe5b14156102f7576101ef87878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610d5992505050565b600481600681111561030557fe5b141561034a576101ef87878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610e6892505050565b600581600681111561035857fe5b141561039d576101ef87878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610e8692505050565b60068160068111156103ab57fe5b14156103f0576101ef87878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610ed492505050565b60405162461bcd60e51b815260040161007e90615b47565b5092959194509250565b61041b82610f13565b156104385760405162461bcd60e51b815260040161007e90615c5a565b6000610442610f9d565b6003810154909150600160c01b810461ffff16600160681b90910463ffffffff16111561050057600061047484610fa2565b600383015490915063ffffffff600160681b9091048116908216118015906104aa5750600382015463ffffffff90811690821611155b156104fe576104b98482610fe2565b60038201546001600160a01b03851660009081526031840160205260409020600a01805467ffffffff00000000191663ffffffff909216640100000000029190911790555b505b61050a838361126f565b60038101546001600160a01b03939093166000908152603190910160205260409020600a01805467ffffffff00000000191663ffffffff909316640100000000029290921790915550565b60008083518551146105795760405162461bcd60e51b815260040161007e906159d7565b610581614ef1565b600080600090506000885167ffffffffffffffff811180156105a257600080fd5b506040519080825280602002602001820160405280156105cc578160200160208202803683370190505b5090506000895167ffffffffffffffff811180156105e957600080fd5b50604051908082528060200260200182016040528015610613578160200160208202803683370190505b5090505b8951831080156106275750845188115b156107dc57876106578a858151811061063c57fe5b6020026020010151876000015161135d90919063ffffffff16565b10156106f05761068f338c8c868151811061066e57fe5b60200260200101518c878151811061068257fe5b60200260200101516113c0565b93508382848151811061069e57fe5b6020026020010181815250506106e66106db8b85815181106106bc57fe5b60200260200101516106cd8e6116b7565b6106d688611782565b6117ca565b60208701519061135d565b6020860152610759565b84516106fd9089906117fd565b89848151811061070957fe5b602002602001018181525050610726338c8c868151811061066e57fe5b93508382848151811061073557fe5b6020026020010181815250506107536106db8b85815181106106bc57fe5b60208601525b61078389848151811061076857fe5b6020026020010151866000015161135d90919063ffffffff16565b85526040850151610794908561135d565b8560400181815250506107ba8b8b85815181106107ad57fe5b602002602001015161185a565b8184815181106107c657fe5b6020908102919091010152600190920191610617565b895183101561080a5760008984815181106107f357fe5b6020026020010181815250508260010192506107dc565b84516040516001600160a01b038d169133917f6008478fd0513693018a0ac8771ada053137941c0d833295a27629af7a3ab56b9161084d918f918f9189906156b9565b60405180910390a3604051600090339081907f4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb9061088e9086908f9061575c565b60405180910390a45050825186146108b85760405162461bcd60e51b815260040161007e906158e6565b6108cb8984600001518560400151611881565b6001600160a01b03891660009081526039602052604090819020549084015161091491339161090f916106db919063ffffffff600160401b90910481169061197d16565b6119d6565b826020015183604001519450945050505094509492505050565b600080610939610f9d565b6001600160a01b038516600090815260398201602052604090205490915060e01b7fffffffff00000000000000000000000000000000000000000000000000000000166109985760405162461bcd60e51b815260040161007e90615b7e565b6001600160a01b0384166000908152603982016020526040812054819030906109ea9088907c0100000000000000000000000000000000000000000000000000000000810460f81b9060e01b89611cac565b6040516109f7919061565b565b600060405180830381855afa9150503d8060008114610a32576040519150601f19603f3d011682016040523d82523d6000602084013e610a37565b606091505b509150915081610a54578051610a4c57600080fd5b805181602001fd5b6020015195945050505050565b60008083118015610a725750600084115b610a8e5760405162461bcd60e51b815260040161007e90615cc8565b610a99858385611dc3565b9092509050610ac433610abf84610ab9610ab28a611e1d565b889061197d565b9061135d565b611e59565b610acf858585611f91565b610ade33868387876000612051565b949350505050565b600081806020019051810190610afc91906153c5565b90505b919050565b6000806000806000806000610b18886122dd565b925092509250610b29838383612304565b919973bea0000029ad1c77d3d5d23ba2d8893db9d1efab99509097509095509350505050565b6000806000806000806000610b63886122dd565b925092509250610b748383836123fa565b73bea0000029ad1c77d3d5d23ba2d8893db9d1efab9a92995090975095509350505050565b731bea3ccd22f4ebd3d37d731ba31eeca95713716d731bea0050e63e05fbb5d8ba2f10cf5800b62244496000808080610bd187612486565b915091506000610c03610be26124a8565b610bfd610bed612547565b610bf78b87612604565b9061197d565b906126ac565b9050600080610c30610c158987612604565b8473bea0e11282e2bb5893bece110cf199501e872bad612713565b91509150610c3e88826128fe565b9550610c4a88826129ae565b604051630852cd8d60e31b81526001600160a01b038916906342966c6890610c7690899060040161582f565b600060405180830381600087803b158015610c9057600080fd5b505af1158015610ca4573d6000803e3d6000fd5b50505050610cc8610cb3612547565b610bfd610cbe6124a8565b610bf78d876128fe565b9650610cd48983612a3f565b6040517f40c10f190000000000000000000000000000000000000000000000000000000081526001600160a01b038a16906340c10f1990610d1b9030908b906004016156a0565b600060405180830381600087803b158015610d3557600080fd5b505af1158015610d49573d6000803e3d6000fd5b5050505050505050509193509193565b731bea0050e63e05fbb5d8ba2f10cf5800b6224449731bea3ccd22f4ebd3d37d731ba31eeca95713716d6000808080610d9187612486565b915091506000610dad610da2612547565b610bfd610bed6124a8565b9050600080610dda610dbf8987612604565b8473bea0e11282e2bb5893bece110cf199501e872bad612ad0565b91509150610de888826128fe565b9550610df488826129ae565b604051630852cd8d60e31b81526001600160a01b038916906342966c6890610e2090899060040161582f565b600060405180830381600087803b158015610e3a57600080fd5b505af1158015610e4e573d6000803e3d6000fd5b50505050610cc8610e5d6124a8565b610bfd610cbe612547565b600080600080610e7785612b4c565b96879650909450849350915050565b6000806000806000806000610e9a886122dd565b92509250925080965073bea0000029ad1c77d3d5d23ba2d8893db9d1efab9550610ec5838383612713565b97999698509695945050505050565b6000806000806000806000610ee8886122dd565b92509250925073bea0000029ad1c77d3d5d23ba2d8893db9d1efab9650809550610ec5838383612ad0565b600080610f1e610f9d565b6001600160a01b03841660009081526031820160205260409020600a0154909150640100000000900463ffffffff1615801590610f96575060038101546001600160a01b03841660009081526031830160205260409020600a0154600160c01b90910461ffff1664010000000090910463ffffffff16105b9392505050565b600090565b600080610fad610f9d565b6001600160a01b03939093166000908152603193909301602052505060409020600a0154640100000000900463ffffffff1690565b6000610fec610f9d565b6001600160a01b03841660009081526031820160205260409020600e01549091506110785760038101546001600160a01b038416600090815260319092016020526040909120600a0180546bffffffff00000000000000001916600160681b90920463ffffffff16600160401b02919091176fffffffff0000000000000000000000001916905561126b565b600381015463ffffffff80841669010000000000000000009092041611156110fc576110a383612b63565b6001600160a01b0384166000908152603183016020526040902060148101919091556003820154600a90910180546bffffffff0000000000000000191664010000000090920463ffffffff16600160401b029190911790555b600381015471010000000000000000000000000000000000900460ff161561120457600381015463ffffffff808416600160681b9092041611156111995760038101546001600160a01b03841660009081526031830160205260409020600a810180546fffffffff0000000000000000000000001916600160681b90930463ffffffff16600160601b0292909217909155600e8101546012909101555b6003810154640100000000810463ffffffff908116600160681b9092041614156111ff576003810154640100000000900463ffffffff166000908152603d820160209081526040808320546001600160a01b038716845260318501909252909120601301555b611269565b6001600160a01b03831660009081526031820160205260409020600a0154600160601b900463ffffffff1615611269576001600160a01b03831660009081526031820160205260409020600a0180546fffffffff000000000000000000000000191690555b505b5050565b6000611279610f9d565b90506000611286836116b7565b6001600160a01b03858116600090815260318501602090815260408083209388168352601a90930190522054909150600b81900b90600160601b90046001600160801b031680156112fc5782600b0b82600b0b14156112e8575050505061126b565b6112fc866112f7848685612d82565b612d8f565b50506001600160a01b0380851660009081526031909301602090815260408085209286168552601a90920190529091208054600b9290920b6bffffffffffffffffffffffff166bffffffffffffffffffffffff199092169190911790555050565b6000828201838110156113b7576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b90505b92915050565b6000806113cb610f9d565b905060006113d9868661185a565b6001600160a01b038816600090815260318401602090815260408083208484526019019091529020546001600160801b03600160801b82048116955091925016808511156114395760405162461bcd60e51b815260040161007e90615b10565b808510156115ca57600061145182610bfd888861197d565b9050600061145f86836117fd565b9050600061146d84896117fd565b6001600160a01b038c1660009081526031880160209081526040808320898452601901909152902080546001600160801b03858116600160801b028482166fffffffffffffffffffffffffffffffff19909316929092171617905590506115516114d684611782565b8760310160008e6001600160a01b03166001600160a01b03168152602001908152602001600020601a0160008d6001600160a01b03166001600160a01b03168152602001908152602001600020600001600c9054906101000a90046001600160801b03166001600160801b0316612ea690919063ffffffff16565b6001600160a01b03808d166000908152603190980160209081526040808a20928e168a52601a909201905290962080546001600160801b0397909716600160601b027fffffffff00000000000000000000000000000000ffffffffffffffffffffffff90971696909617909555509350610ade92505050565b80156115fa576001600160a01b038816600090815260318401602090815260408083208584526019019091528120555b6001600160a01b0388811660009081526031850160209081526040808320938b168352601a9093019052205461164090600160601b90046001600160801b031685612ea6565b6001600160a01b03808a166000908152603190950160209081526040808720928b168752601a909201905290932080546001600160801b0394909416600160601b027fffffffff00000000000000000000000000000000ffffffffffffffffffffffff909416939093179092555050949350505050565b6000806116c2610f9d565b6001600160a01b0384166000908152603982016020526040902054600382015491925061175291620f424091611749916117139163ffffffff918216600b0b91600160601b909104811690612f0f16565b6001600160a01b038716600090815260398601602052604090205463ffffffff6401000000009091048116600b0b9190612f8716565b600b0b90613057565b6001600160a01b03909316600090815260399091016020526040902054600160801b9004600b0b91909101919050565b6000600160801b82106117c65760405162461bcd60e51b8152600401808060200182810382526027815260200180615dd16027913960400191505060405180910390fd5b5090565b6000806117e8836117df600b87900b88612f0f565b600b0b90612f87565b600b0b6001600160801b031695945050505050565b600082821115611854576040805162461bcd60e51b815260206004820152601e60248201527f536166654d6174683a207375627472616374696f6e206f766572666c6f770000604482015290519081900360640190fd5b50900390565b6bffffffffffffffffffffffff1660609190911b6bffffffffffffffffffffffff19161790565b600061188b610f9d565b90506118c361189984611782565b6001600160a01b03861660009081526038840160205260409020546001600160801b031690612ea6565b6001600160a01b0385166000908152603883016020526040902080546fffffffffffffffffffffffffffffffff19166001600160801b039290921691909117905561194161191083611782565b6001600160a01b0386166000908152603884016020526040902054600160801b90046001600160801b031690612ea6565b6001600160a01b03909416600090815260389091016020526040902080546001600160801b03948516600160801b029416939093179092555050565b60008261198c575060006113ba565b8282028284828161199957fe5b04146113b75760405162461bcd60e51b8152600401808060200182810382526021815260200180615e196021913960400191505060405180910390fd5b60006119e0610f9d565b9050816119ed575061126b565b60006119f761312c565b15611aee57603c820154601b830154601d840154611a2592909186916001600160801b031690036001613165565b6001600160a01b038516600090815260318401602052604081206008810154600a909101549293509091611a6e9190610bfd90600160801b90046001600160801b03168761197d565b9050611ab0611a7c82611782565b6001600160a01b03871660009081526031860160205260409020600a0154600160801b90046001600160801b031690612ea6565b6001600160a01b03861660009081526031850160205260409020600a0180546001600160801b03928316600160801b02921691909117905550611b08565b601b820154601d830154611b059185906001613165565b90505b6001600160a01b03841660009081526031830160205260409020600e0154811115611b4d57506001600160a01b03831660009081526031820160205260409020600e01545b601b820154611b5c90846117fd565b601b8301556001600160a01b0384166000908152603183016020526040902060080154611b8990846117fd565b6001600160a01b0385166000908152603184016020526040902060080155601d820154611bb690826117fd565b601d8301556001600160a01b03841660009081526031830160205260409020600e0154611be390826117fd565b6001600160a01b03851660009081526031840160205260409020600e0155600382015471010000000000000000000000000000000000900460ff1615611c5d57601a820154611c3290826117fd565b601a8301556001600160a01b03841660009081526031830160205260409020600e8101546012909101555b836001600160a01b03167fb2d61db64b8ad7535308d2111c78934bc32baf9b7cd3a2e58cba25730003cd588460000383600003604051611c9e929190615838565b60405180910390a250505050565b60607fff000000000000000000000000000000000000000000000000000000000000008416611d4d578282604051602401611ce7919061582f565b60408051601f198184030181529190526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fffffffff00000000000000000000000000000000000000000000000000000000909316929092179091529050610ade565b7f01000000000000000000000000000000000000000000000000000000000000007fff0000000000000000000000000000000000000000000000000000000000000085161415611dab57828583604051602401611ce79291906156a0565b60405162461bcd60e51b815260040161007e90615aa2565b6000806000611dd1866116b7565b9050611df3611de8611de387876126ac565b6131ac565b600b83900b90612f0f565b9150611e0f611e01856131ac565b6117df600b84900b85612f0f565b600b0b925050935093915050565b600080611e28610f9d565b6001600160a01b0393909316600090815260399390930160205250506040902054600160401b900463ffffffff1690565b6000611e63610f9d565b601d810154909150600090611e8b57611e84611e7d6131da565b849061197d565b9050611ea7565b601b820154601d830154611ea49190610bfd908661197d565b90505b601b820154611eb6908461135d565b601b8301556001600160a01b0384166000908152603183016020526040902060080154611ee3908461135d565b6001600160a01b0385166000908152603184016020526040902060080155601d820154611f10908261135d565b601d8301556001600160a01b03841660009081526031830160205260409020600e0154611f3d908261135d565b6001600160a01b038516600081815260318501602052604090819020600e019290925590517fb2d61db64b8ad7535308d2111c78934bc32baf9b7cd3a2e58cba25730003cd5890611c9e9086908590615838565b6000611f9b610f9d565b9050611fd3611fa984611782565b6001600160a01b03861660009081526038840160205260409020546001600160801b0316906131e3565b6001600160a01b0385166000908152603883016020526040902080546fffffffffffffffffffffffffffffffff19166001600160801b039290921691909117905561194161202083611782565b6001600160a01b0386166000908152603884016020526040902054600160801b90046001600160801b0316906131e3565b600061205b610f9d565b90506000612069878761185a565b90506120af61207786611782565b6001600160a01b038a16600090815260318501602090815260408083208684526019019091529020546001600160801b0316906131e3565b6001600160a01b03891660009081526031840160209081526040808320858452601901909152902080546fffffffffffffffffffffffffffffffff19166001600160801b039290921691909117905561214961210a85611782565b6001600160a01b038a1660009081526031850160209081526040808320868452601901909152902054600160801b90046001600160801b0316906131e3565b6001600160a01b03808a166000908152603185016020908152604080832086845260198101835281842080546001600160801b03978816600160801b02908816179055938c168352601a909301905220546121ad91600160601b90910416856131e3565b6001600160a01b03808a1660009081526031850160209081526040808320938c168352601a909301905290812080546001600160801b0393909316600160601b027fffffffff00000000000000000000000000000000ffffffffffffffffffffffff9093169290921790915583600181111561222557fe5b141561228457876001600160a01b031660006001600160a01b0316336001600160a01b03167fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62848960405161227b929190615838565b60405180910390a45b866001600160a01b0316886001600160a01b03167ff4d42fc7416f300569832aee6989201c613d31d64b823327915a6a33fe7afa558888886040516122cb93929190615846565b60405180910390a35050505050505050565b6000806000838060200190518101906122f69190615452565b919790965090945092505050565b600080600061231284613249565b9050600081116123345760405162461bcd60e51b815260040161007e90615bec565b8086116123415785612343565b805b6040805180820182528281526000602082015290517f0b4c7e4d0000000000000000000000000000000000000000000000000000000081529193506001600160a01b03861691630b4c7e4d9161239d918990600401615724565b602060405180830381600087803b1580156123b757600080fd5b505af11580156123cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123ef919061556d565b925050935093915050565b6000806000612408846132ed565b90506000811161242a5760405162461bcd60e51b815260040161007e906159a0565b8086116124375785612439565b805b6040517f1a4d01d20000000000000000000000000000000000000000000000000000000081529092506001600160a01b03851690631a4d01d29061239d9085906000908a90600401615d2d565b6000808280602001905181019061249d919061541e565b909590945092505050565b6000806124b3610f9d565b90506125406124c061338e565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156124f857600080fd5b505afa15801561250c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612530919061556d565b610bfd8360480154610bf76133a6565b9150505b90565b600080612552610f9d565b905061254061255f6133ad565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561259757600080fd5b505afa1580156125ab573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125cf919061556d565b731bea0050e63e05fbb5d8ba2f10cf5800b622444960009081526040808501602052902060010154610bfd90620f424061197d565b60008061260f610f9d565b9050610ade846001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561264d57600080fd5b505afa158015612661573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612685919061556d565b6001600160a01b03861660009081526040808501602052902060010154610bfd908661197d565b6000808211612702576040805162461bcd60e51b815260206004820152601a60248201527f536166654d6174683a206469766973696f6e206279207a65726f000000000000604482015290519081900360640190fd5b81838161270b57fe5b049392505050565b600080600080612722856133c5565b91509150600082116127465760405162461bcd60e51b815260040161007e90615bec565b8187116127535786612755565b815b92506000856001600160a01b0316639d63848a6040518163ffffffff1660e01b815260040160006040518083038186803b15801561279257600080fd5b505afa1580156127a6573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526127ce9190810190615090565b90506127d861363d565b6001600160a01b031663a9059cbb878a6040518363ffffffff1660e01b81526004016128059291906156a0565b602060405180830381600087803b15801561281f57600080fd5b505af1158015612833573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061285791906152f3565b506040517fef4fcafa0000000000000000000000000000000000000000000000000000000081526001600160a01b0387169063ef4fcafa9061289f9030908b906004016156a0565b602060405180830381600087803b1580156128b957600080fd5b505af11580156128cd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128f1919061556d565b9450505050935093915050565b600080612909610f9d565b9050610ade816040016000866001600160a01b03166001600160a01b0316815260200190815260200160002060010154610bfd85876001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561297657600080fd5b505afa15801561298a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bf7919061556d565b60006129b8610f9d565b90506001600160a01b038316731bea3ccd22f4ebd3d37d731ba31eeca95713716d1415612a3557731bea3ccd22f4ebd3d37d731ba31eeca95713716d600090815260408083016020528120600101546048830154612a1c9190610bfd90869061197d565b6048830154909150612a2e90826117fd565b6048830155505b6112698383613655565b6000612a49610f9d565b90506001600160a01b038316731bea3ccd22f4ebd3d37d731ba31eeca95713716d1415612ac657731bea3ccd22f4ebd3d37d731ba31eeca95713716d600090815260408083016020528120600101546048830154612aad9190610bfd90869061197d565b6048830154909150612abf908261135d565b6048830155505b61126983836136ea565b6000806000612ade8461376f565b905060008111612b005760405162461bcd60e51b815260040161007e906159a0565b808611612b0d5785612b0f565b805b9150836001600160a01b0316635fe192c683612b2961363d565b8830426040518663ffffffff1660e01b815260040161239d959493929190615cff565b6000808280602001905181019061249d91906153df565b600080612b6e610f9d565b6001600160a01b038416600090815260318201602052604081206014810154600a82015490955092935091600160601b900463ffffffff1615612c9657600a820154600160401b810463ffffffff908116600160601b909204161415612bd957506013810154612bfe565b50600a810154600160401b900463ffffffff166000908152603d830160205260409020545b6001600160a01b03851660009081526031840160209081526040808320600a0154600160601b900463ffffffff168352603d860190915290205481811115612c90576001600160a01b03861660009081526031850160205260409020601201549091829190820390612c8c90612c859069d3c21bcecceda100000090610bfd90859061197d565b879061135d565b9550505b50612cd2565b506001600160a01b03841660009081526031830160209081526040808320600a0154600160401b900463ffffffff168352603d85019091529020545b612cdb85610fa2565b600384015463ffffffff9182166401000000009091049091161115612d7a57600383015463ffffffff64010000000090910481166000908152603d850160205260408120549091612d2f919084906117fd16565b6001600160a01b03871660009081526031860160205260409020600e0154909150612d7690612d6f9069d3c21bcecceda100000090610bfd90859061197d565b869061135d565b9450505b505050919050565b6000610ade8484846117ca565b6000612d99610f9d565b601d810154909150600090612db357611e84611e7d6131da565b601b820154601d830154612dcc9190610bfd908661197d565b9050612dd661312c565b15611ea757603c820154601b830154601d840154600092612e18926001600160801b0380831690910392610bfd928992610bf79291600160801b90041661135d565b90506000612e27838303611782565b603c850154909150612e4990600160801b90046001600160801b0316826131e3565b603c850180546001600160801b03908116600160801b9382168402179091556001600160a01b03881660009081526031870160205260409020600a01805482169390911690910291909117905550601b820154611eb6908461135d565b6000826001600160801b0316826001600160801b03161115611854576040805162461bcd60e51b815260206004820152601e60248201527f536166654d6174683a207375627472616374696f6e206f766572666c6f770000604482015290519081900360640190fd5b6000818303600b83900b8213801590612f2e575083600b0b81600b0b13155b80612f4c5750600083600b0b128015612f4c575083600b0b81600b0b135b6113b75760405162461bcd60e51b8152600401808060200182810382526024815260200180615e616024913960400191505060405180910390fd5b600082600b0b60001415612f9d575060006113ba565b82600b0b600019148015612fc15750600b82900b6b7fffffffffffffffffffffff19145b15612ffd5760405162461bcd60e51b8152600401808060200182810382526027815260200180615e3a6027913960400191505060405180910390fd5b6000828402905082600b0b84600b0b82600b0b8161301757fe5b05600b0b146113b75760405162461bcd60e51b8152600401808060200182810382526027815260200180615e3a6027913960400191505060405180910390fd5b600081600b0b600014156130b2576040805162461bcd60e51b815260206004820181905260248201527f5369676e6564536166654d6174683a206469766973696f6e206279207a65726f604482015290519081900360640190fd5b81600b0b6000191480156130d65750600b83900b6b7fffffffffffffffffffffff19145b156131125760405162461bcd60e51b8152600401808060200182810382526021815260200180615df86021913960400191505060405180910390fd5b600082600b0b84600b0b8161312357fe5b05949350505050565b600080613137610f9d565b60030154600a73010000000000000000000000000000000000000090910463ffffffff164303111592915050565b600080613173868686613b18565b9050600183600281111561318357fe5b14801561319a57506000848061319557fe5b868809115b156131a3576001015b95945050505050565b60006b7fffffffffffffffffffffff8211156117c65760405162461bcd60e51b815260040161007e90615943565b64e8d4a5100090565b60008282016001600160801b0380851690821610156113b7576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b600080826001600160a01b03166314f059796040518163ffffffff1660e01b8152600401604080518083038186803b15801561328457600080fd5b505afa158015613298573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132bc91906151f1565b905060006132ca8483613bbe565b825190915081116132e057600092505050610aff565b8151610ade9082906117fd565b600080826001600160a01b03166314f059796040518163ffffffff1660e01b8152600401604080518083038186803b15801561332857600080fd5b505afa15801561333c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061336091906151f1565b9050600061336e8483613bbe565b8251909150811061338457600092505050610aff565b610ade8282613c0d565b731bea3ccd22f4ebd3d37d731ba31eeca95713716d90565b621cc1b090565b731bea0050e63e05fbb5d8ba2f10cf5800b622444990565b6000806000836001600160a01b0316639d63848a6040518163ffffffff1660e01b815260040160006040518083038186803b15801561340357600080fd5b505afa158015613417573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261343f9190810190615090565b90506000846001600160a01b0316630902f1ac6040518163ffffffff1660e01b815260040160006040518083038186803b15801561347c57600080fd5b505afa158015613490573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526134b8919081019061526f565b90506000856001600160a01b03166310dd08306040518163ffffffff1660e01b815260040160006040518083038186803b1580156134f557600080fd5b505afa158015613509573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526135319190810190615499565b90506060600061354085613ce0565b9097509092509050806135655760405162461bcd60e51b815260040161007e90615ad9565b825160208401516040516316a1119f60e21b81526000926001600160a01b031691635a84467c9161359e9189918c9189916004016157a6565b60206040518083038186803b1580156135b657600080fd5b505afa1580156135ca573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135ee919061556d565b90508487815181106135fc57fe5b602002602001015181116136195760009750505050505050613638565b84878151811061362557fe5b6020026020010151810397505050505050505b915091565b73bea0000029ad1c77d3d5d23ba2d8893db9d1efab90565b600061365f610f9d565b6001600160a01b0384166000908152604080830160205290206001015490915061368990836117fd565b6001600160a01b0384166000818152604080850160205280822060010193909355915190917f034be0cb985c00ed623355853288b175a6c0bd25ed03d64e9895ccec774af9e7916136dd918690039061582f565b60405180910390a2505050565b60006136f4610f9d565b6001600160a01b0384166000908152604080830160205290206001015490915061371e908361135d565b6001600160a01b03841660008181526040808501602052908190206001019290925590517f034be0cb985c00ed623355853288b175a6c0bd25ed03d64e9895ccec774af9e7906136dd90859061582f565b600080826001600160a01b0316639d63848a6040518163ffffffff1660e01b815260040160006040518083038186803b1580156137ab57600080fd5b505afa1580156137bf573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526137e79190810190615090565b90506000836001600160a01b0316630902f1ac6040518163ffffffff1660e01b815260040160006040518083038186803b15801561382457600080fd5b505afa158015613838573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052613860919081019061526f565b90506000846001600160a01b03166310dd08306040518163ffffffff1660e01b815260040160006040518083038186803b15801561389d57600080fd5b505afa1580156138b1573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526138d99190810190615499565b905060008060006138e986613ce0565b9250925092508061390c5760405162461bcd60e51b815260040161007e90615ad9565b835160208501516040516316a1119f60e21b81526000926001600160a01b031691635a84467c91613945918a9188918a916004016157a6565b60206040518083038186803b15801561395d57600080fd5b505afa158015613971573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613995919061556d565b9050808684815181106139a457fe5b6020026020010151116139c1576000975050505050505050610aff565b845160208601516040517f14c15fc00000000000000000000000000000000000000000000000000000000081526000926001600160a01b0316916314c15fc091613a0f918b91600401615781565b60206040518083038186803b158015613a2757600080fd5b505afa158015613a3b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a5f919061556d565b905081878581518110613a6e57fe5b602002602001018181525050613b0a86600001516001600160a01b03166314c15fc08989602001516040518363ffffffff1660e01b8152600401613ab3929190615781565b60206040518083038186803b158015613acb57600080fd5b505afa158015613adf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613b03919061556d565b82906117fd565b9a9950505050505050505050565b6000808060001985870986860292508281109083900303905080613b4957838281613b3f57fe5b0492505050610f96565b808411613b5557600080fd5b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b60006001600160a01b03831673c9c32cd16bf7efb85ff14e0c8603cc90f6f2ee491415613bf557613bee82613e2b565b90506113ba565b60405162461bcd60e51b815260040161007e90615889565b600080613c18613ec8565b6001600160a01b03166376a2f0f06040518163ffffffff1660e01b815260040160206040518083038186803b158015613c5057600080fd5b505afa158015613c64573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613c88919061556d565b90506000613c9585613ee0565b90506000613ca38284613ef7565b90506000613cb98688835b6020020151906117fd565b9050613cc781888487614003565b9050613cd58188848761416c565b979650505050505050565b606060008060019050835167ffffffffffffffff81118015613d0157600080fd5b50604051908082528060200260200182016040528015613d2b578160200160208202803683370190505b509250600019915060005b8451811015613e0157848181518110613d4b57fe5b60200260200101516001600160a01b031673bea0000029ad1c77d3d5d23ba2d8893db9d1efab6001600160a01b03161415613da457809250620f4240848281518110613d9357fe5b602002602001018181525050613df9565b613dc0858281518110613db357fe5b602002602001015161422f565b848281518110613dcc57fe5b602002602001018181525050838181518110613de457fe5b602002602001015160001415613df957600091505b600101613d36565b50600019821415613e245760405162461bcd60e51b815260040161007e90615bb5565b9193909250565b6000610afc6c0c9f2c9cd04674edea40000000610bfd613e496142a5565b6001600160a01b031663bb7b8b806040518163ffffffff1660e01b815260040160206040518083038186803b158015613e8157600080fd5b505afa158015613e95573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613eb9919061556d565b8560015b60200201519061197d565b73c9c32cd16bf7efb85ff14e0c8603cc90f6f2ee4990565b613ee8614f12565b610afc8264e8d4a510006142bd565b6000806000805b6002811015613f2557858160028110613f1357fe5b60200201519290920191600101613efe565b5081613f36576000925050506113ba565b90915081906002840260005b610100811015613fea578460005b6002811015613f82576002898260028110613f6757fe5b60200201510287830281613f7757fe5b049150600101613f50565b508593506003810260646063198501860204018660028302606486890204010281613fa957fe5b0495508386118015613fbe5750600184870311155b15613fcd5750505050506113ba565b600186850311613fe15750505050506113ba565b50600101613f42565b5060405162461bcd60e51b815260040161007e90615c91565b60008061400f85613ee0565b90506000614026614021888884613cae565b614347565b9050600061405860405180604001604052808481526020018560016002811061404b57fe5b6020020151905286613ef7565b9050614062614f12565b600061407d846140778a610bfd878a87613ebd565b906117fd565b90506140a56402540be400614095621e84808461197d565b8161409c57fe5b04866000613cae565b82526140c26140ba89610bfd86896001613ebd565b866001613cae565b90506140ea6402540be4006140da621e84808461197d565b816140e157fe5b04866001613cae565b602083015260006140fd88828587614358565b9050600061410c828583613cae565b905061412161411c8260016117fd565b614441565b9050600061413361411c888a84613cae565b905061415b6141546402540be400610bfd64012a05f200610bf786886117fd565b829061135d565b9d9c50505050505050505050505050565b6000614179858583613cae565b8452600061418685613ee0565b905060006141948285613ef7565b905060006141a286836117fd565b905061422386610bfd6141b3613ec8565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156141eb57600080fd5b505afa1580156141ff573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e7d919061556d565b98975050505050505050565b60006001600160a01b03821673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2141561428d576000614260614452565b905080614271576000915050610aff565b61428569d3c21bcecceda1000000826126ac565b915050610aff565b60405162461bcd60e51b815260040161007e90615a6b565b73bebc44782c7db0a1a60cb6fe97d0b483032ff1c790565b6142c5614f12565b6113b783836142d26142a5565b6001600160a01b031663bb7b8b806040518163ffffffff1660e01b815260040160206040518083038186803b15801561430a57600080fd5b505afa15801561431e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614342919061556d565b614527565b6000610afc8264e8d4a5100061197d565b60008080808460028902825b60028110156143af5789811461438c5788816002811061438057fe5b60200201519450614391565b6143a7565b9484019460028502838902816143a357fe5b0492505b600101614364565b5060028102606488840202816143c157fe5b04915060008160648902816143d257fe5b048601905087965060005b60ff811015613fea57879450888289600202010384898a0201816143fd57fe5b04975084881180156144125750600185890311155b156144235750505050505050610ade565b6001888603116144395750505050505050610ade565b6001016143dd565b6000610afc8264e8d4a510006126ac565b60008061445d614561565b90508061446e576000915050612544565b6000614478614719565b905060006144868284614795565b9050660aa87bee5380008110156144b0576144a66002610bfd858561135d565b9350505050612544565b60006144ba6147d7565b905060006144c88286614795565b90508281101561450957662386f26fc100008110156144fc576144f06002610bfd878561135d565b95505050505050612544565b8495505050505050612544565b662386f26fc100008310156144fc576144f06002610bfd878761135d565b61452f614f12565b61453b83856000613ebd565b8152614555670de0b6b3a7640000610bfd84876001613ebd565b60208201529392505050565b600080735f4ec3df9cbd43714fe2740f5e3616155c5b84196001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156145b157600080fd5b505afa9250505080156145e1575060408051601f3d908101601f191682019092526145de918101906155d4565b60015b6145ef576000915050612544565b9050735f4ec3df9cbd43714fe2740f5e3616155c5b84196001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a06040518083038186803b15801561463e57600080fd5b505afa92505050801561466e575060408051601f3d908101601f1916820190925261466b91810190615585565b60015b61467c576000915050612544565b69ffffffffffffffffffff851661469c5760009650505050505050612544565b8115806146a857504282115b156146bc5760009650505050505050612544565b6138406146c942846117fd565b11156146de5760009650505050505050612544565b600084136146f55760009650505050505050612544565b61470c60ff8716600a0a610bfd86620f424061197d565b9650505050505050612544565b600080600061473e7388e6a0c2ddd26feeb64f039a2c41296fcb3f564061038461484c565b915091508161475257600092505050612544565b61478e81670de0b6b3a764000073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc273a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48614a02565b9250505090565b60006147ad82610bfd85670de0b6b3a764000061197d565b90508183116147c65780670de0b6b3a7640000036113b7565b670de0b6b3a763ffff190192915050565b60008060006147fc7311b815efb8f581194ae79006d24e0d814b7697f661038461484c565b915091508161481057600092505050612544565b61478e81670de0b6b3a764000073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc273dac17f958d2ee523a2206206994597c13d831ec7614a02565b60008063ffffffff83166148725760405162461bcd60e51b815260040161007e90615a34565b60408051600280825260608201835260009260208301908036833701905050905083816000815181106148a157fe5b602002602001019063ffffffff16908163ffffffff16815250506000816001815181106148ca57fe5b63ffffffff909216602092830291909101909101526040517f883bdbfd0000000000000000000000000000000000000000000000000000000081526001600160a01b0386169063883bdbfd906149249084906004016157e5565b60006040518083038186803b15801561493c57600080fd5b505afa92505050801561497157506040513d6000823e601f3d908101601f1916820160405261496e9190810190615129565b60015b61497a576149fa565b60008260008151811061498957fe5b60200260200101518360018151811061499e57fe5b60200260200101510390508663ffffffff168160060b816149bb57fe5b05945060008160060b1280156149e557508663ffffffff168160060b816149de57fe5b0760060b15155b156149f257600019909401935b600195505050505b509250929050565b600080614a0e86614af4565b90506001600160801b036001600160a01b03821611614a7d576001600160a01b0380821680029084811690861610614a5d57614a58600160c01b876001600160801b031683614e42565b614a75565b614a7581876001600160801b0316600160c01b614e42565b925050614aeb565b6000614a976001600160a01b03831680600160401b614e42565b9050836001600160a01b0316856001600160a01b031610614acf57614aca600160801b876001600160801b031683614e42565b614ae7565b614ae781876001600160801b0316600160801b614e42565b9250505b50949350505050565b60008060008360020b12614b0b578260020b614b13565b8260020b6000035b9050620d89e8811115614b6d576040805162461bcd60e51b815260206004820152600160248201527f5400000000000000000000000000000000000000000000000000000000000000604482015290519081900360640190fd5b600060018216614b8157600160801b614b93565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615614bc7576ffff97272373d413259a46990580e213a0260801c5b6004821615614be6576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615614c05576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615614c24576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615614c43576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615614c62576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615614c81576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615614ca1576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615614cc1576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615614ce1576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615614d01576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615614d21576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615614d41576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615614d61576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615614d81576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615614da2576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615614dc2576e5d6af8dedb81196699c329225ee6040260801c5b62040000821615614de1576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615614dfe576b048a170391f7dc42444e8fa20260801c5b60008460020b1315614e19578060001981614e1557fe5b0490505b640100000000810615614e2d576001614e30565b60005b60ff16602082901c0192505050919050565b6000808060001985870986860292508281109083900303905080614e785760008411614e6d57600080fd5b508290049050610f96565b808411614e8457600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b60405180606001604052806000815260200160008152602001600081525090565b60405180604001604052806002906020820280368337509192915050565b600082601f830112614f40578081fd5b81356020614f55614f5083615d6a565b615d46565b8281528181019085830183850287018401881015614f71578586fd5b855b85811015614f9d57813580600b0b8114614f8b578788fd5b84529284019290840190600101614f73565b5090979650505050505050565b600082601f830112614fba578081fd5b81516020614fca614f5083615d6a565b8281528181019085830183850287018401881015614fe6578586fd5b855b85811015614f9d578151614ffb81615db8565b84529284019290840190600101614fe8565b600082601f83011261501d578081fd5b8135602061502d614f5083615d6a565b8281528181019085830183850287018401881015615049578586fd5b855b85811015614f9d5781358452928401929084019060010161504b565b805160078110610aff57600080fd5b805169ffffffffffffffffffff81168114610aff57600080fd5b600060208083850312156150a2578182fd5b825167ffffffffffffffff8111156150b8578283fd5b8301601f810185136150c8578283fd5b80516150d6614f5082615d6a565b81815283810190838501858402850186018910156150f2578687fd5b8694505b8385101561511d57805161510981615db8565b8352600194909401939185019185016150f6565b50979650505050505050565b6000806040838503121561513b578081fd5b825167ffffffffffffffff80821115615152578283fd5b818501915085601f830112615165578283fd5b81516020615175614f5083615d6a565b82815281810190858301838502870184018b1015615191578788fd5b8796505b848710156151c15780518060060b81146151ad578889fd5b835260019690960195918301918301615195565b50918801519196509093505050808211156151da578283fd5b506151e785828601614faa565b9150509250929050565b600060408284031215615202578081fd5b82601f830112615210578081fd5b6040516040810181811067ffffffffffffffff8211171561522d57fe5b8060405250808385604086011115615243578384fd5b835b6002811015615264578151835260209283019290910190600101615245565b509195945050505050565b60006020808385031215615281578182fd5b825167ffffffffffffffff811115615297578283fd5b8301601f810185136152a7578283fd5b80516152b5614f5082615d6a565b81815283810190838501858402850186018910156152d1578687fd5b8694505b8385101561511d5780518352600194909401939185019185016152d5565b600060208284031215615304578081fd5b815180151581146113b7578182fd5b60008060008060608587031215615328578182fd5b843567ffffffffffffffff8082111561533f578384fd5b818701915087601f830112615352578384fd5b813581811115615360578485fd5b886020828501011115615371578485fd5b60209283019650945090860135908082111561538b578384fd5b61539788838901614f30565b935060408701359150808211156153ac578283fd5b506153b98782880161500d565b91505092959194509250565b6000602082840312156153d6578081fd5b6113b782615067565b6000806000606084860312156153f3578081fd5b6153fc84615067565b925060208401519150604084015161541381615db8565b809150509250925092565b600080600060608486031215615432578081fd5b61543b84615067565b925060208401519150604084015190509250925092565b60008060008060808587031215615467578182fd5b61547085615067565b93506020850151925060408501519150606085015161548e81615db8565b939692955090935050565b600060208083850312156154ab578182fd5b825167ffffffffffffffff808211156154c2578384fd5b90840190604082870312156154d5578384fd5b6040516040810181811083821117156154ea57fe5b60405282516154f881615db8565b8152828401518281111561550a578586fd5b80840193505086601f84011261551e578485fd5b82518281111561552a57fe5b61553c601f8201601f19168601615d46565b92508083528785828601011115615551578586fd5b61556081868501878701615d88565b5092830152509392505050565b60006020828403121561557e578081fd5b5051919050565b600080600080600060a0868803121561559c578283fd5b6155a586615076565b94506020860151935060408601519250606086015191506155c860808701615076565b90509295509295909350565b6000602082840312156155e5578081fd5b815160ff811681146113b7578182fd5b6000815180845260208085019450808401835b8381101561562457815187529582019590820190600101615608565b509495945050505050565b60008151808452615647816020860160208601615d88565b601f01601f19169290920160200192915050565b6000825161566d818460208701615d88565b9190910192915050565b6001600160a01b0394851681529290931660208301526040820152606081019190915260800190565b6001600160a01b03929092168252602082015260400190565b6080808252855190820181905260009060209060a0840190828901845b828110156156f5578151600b0b845292840192908401906001016156d6565b5050508381038285015261570981886155f5565b9150508460408401528281036060840152613cd581856155f5565b60608101818460005b600281101561574c57815183526020928301929091019060010161572d565b5050508260408301529392505050565b60006040825261576f60408301856155f5565b82810360208401526131a381856155f5565b60006040825261579460408301856155f5565b82810360208401526131a3818561562f565b6000608082526157b960808301876155f5565b85602084015282810360408401526157d181866155f5565b90508281036060840152613cd5818561562f565b6020808252825182820181905260009190848201906040850190845b8181101561582357835163ffffffff1683529284019291840191600101615801565b50909695505050505050565b90815260200190565b918252602082015260400190565b600b9390930b83526020830191909152604082015260600190565b600b9590950b8552602085019390935260408401919091526060830152608082015260a00190565b60208082526026908201527f436f6e766572743a204e6f7420612077686974656c697374656420437572766560408201527f20706f6f6c2e0000000000000000000000000000000000000000000000000000606082015260800190565b60208082526023908201527f436f6e766572743a204e6f7420656e6f75676820746f6b656e732072656d6f7660408201527f65642e0000000000000000000000000000000000000000000000000000000000606082015260800190565b60208082526027908201527f53616665436173743a2076616c756520646f65736e27742066697420696e206160408201527f6e20696e74393600000000000000000000000000000000000000000000000000606082015260800190565b60208082526017908201527f436f6e766572743a2050206d757374206265203c20312e000000000000000000604082015260600190565b60208082526029908201527f436f6e766572743a207374656d732c20616d6f756e747320617265206469666660408201527f206c656e677468732e0000000000000000000000000000000000000000000000606082015260800190565b60208082526002908201527f4250000000000000000000000000000000000000000000000000000000000000604082015260600190565b6020808252601c908201527f4f7261636c653a20546f6b656e206e6f7420737570706f727465642e00000000604082015260600190565b60208082526018908201527f53696c6f3a20496e76616c696420656e636f6465547970650000000000000000604082015260600190565b6020808252601a908201527f436f6e766572743a20555344204f7261636c65206661696c6564000000000000604082015260600190565b6020808252601c908201527f53696c6f3a2043726174652062616c616e636520746f6f206c6f772e00000000604082015260600190565b60208082526018908201527f436f6e766572743a20496e76616c6964207061796c6f61640000000000000000604082015260600190565b6020808252601b908201527f53696c6f3a20546f6b656e206e6f742077686974656c69737465640000000000604082015260600190565b60208082526011908201527f4265616e206e6f7420696e2057656c6c2e000000000000000000000000000000604082015260600190565b60208082526018908201527f436f6e766572743a2050206d757374206265203e3d20312e0000000000000000604082015260600190565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b60208082526016908201527f53696c6f3a204d6967726174696f6e206e656564656400000000000000000000604082015260600190565b60208082526018908201527f50726963653a20436f6e76657267656e63652066616c73650000000000000000604082015260600190565b6020808252601c908201527f436f6e766572743a20424456206f7220616d6f756e7420697320302e00000000604082015260600190565b9485526001600160a01b03938416602086015260408501929092529091166060830152608082015260a00190565b928352600f9190910b6020830152604082015260600190565b60405181810167ffffffffffffffff81118282101715615d6257fe5b604052919050565b600067ffffffffffffffff821115615d7e57fe5b5060209081020190565b60005b83811015615da3578181015183820152602001615d8b565b83811115615db2576000848401525b50505050565b6001600160a01b0381168114615dcd57600080fd5b5056fe53616665436173743a2076616c756520646f65736e27742066697420696e2031323820626974735369676e6564536166654d6174683a206469766973696f6e206f766572666c6f77536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f775369676e6564536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f775369676e6564536166654d6174683a207375627472616374696f6e206f766572666c6f77a264697066735822122026a7fda679202f575a92dda1c40a7dbf869828a16cb833f3839d3ec32aa699ba64736f6c63430007060033

Deployed Bytecode

0x60806040526004361061001e5760003560e01c8063b362a6e814610023575b600080fd5b610036610031366004615313565b610050565b604051610047959493929190615861565b60405180910390f35b600080600080600060026000601e015414156100875760405162461bcd60e51b815260040161007e90615c23565b60405180910390fd5b6002601e556000808061009a8c8c610153565b9950975090935091506100ad3383610412565b6100b73384610412565b6100c3828b8b8a610555565b9550905060006100d3848861092e565b90508581116100e257856100e4565b805b94506100f284888785610a61565b9850336001600160a01b03167f3f7117900f070f33613da64255c3e8a5b791ff071197653712e53fde9c3dab3d84868b8b6040516101339493929190615677565b60405180910390a250506001601e55509499939850919650945092509050565b600080600080600061019a87878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610ae692505050565b905060008160068111156101aa57fe5b14156101fe576101ef87878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610b0492505050565b92975090955093509150610408565b600181600681111561020c57fe5b1415610251576101ef87878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610b4f92505050565b600281600681111561025f57fe5b14156102a4576101ef87878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610b9992505050565b60038160068111156102b257fe5b14156102f7576101ef87878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610d5992505050565b600481600681111561030557fe5b141561034a576101ef87878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610e6892505050565b600581600681111561035857fe5b141561039d576101ef87878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610e8692505050565b60068160068111156103ab57fe5b14156103f0576101ef87878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610ed492505050565b60405162461bcd60e51b815260040161007e90615b47565b5092959194509250565b61041b82610f13565b156104385760405162461bcd60e51b815260040161007e90615c5a565b6000610442610f9d565b6003810154909150600160c01b810461ffff16600160681b90910463ffffffff16111561050057600061047484610fa2565b600383015490915063ffffffff600160681b9091048116908216118015906104aa5750600382015463ffffffff90811690821611155b156104fe576104b98482610fe2565b60038201546001600160a01b03851660009081526031840160205260409020600a01805467ffffffff00000000191663ffffffff909216640100000000029190911790555b505b61050a838361126f565b60038101546001600160a01b03939093166000908152603190910160205260409020600a01805467ffffffff00000000191663ffffffff909316640100000000029290921790915550565b60008083518551146105795760405162461bcd60e51b815260040161007e906159d7565b610581614ef1565b600080600090506000885167ffffffffffffffff811180156105a257600080fd5b506040519080825280602002602001820160405280156105cc578160200160208202803683370190505b5090506000895167ffffffffffffffff811180156105e957600080fd5b50604051908082528060200260200182016040528015610613578160200160208202803683370190505b5090505b8951831080156106275750845188115b156107dc57876106578a858151811061063c57fe5b6020026020010151876000015161135d90919063ffffffff16565b10156106f05761068f338c8c868151811061066e57fe5b60200260200101518c878151811061068257fe5b60200260200101516113c0565b93508382848151811061069e57fe5b6020026020010181815250506106e66106db8b85815181106106bc57fe5b60200260200101516106cd8e6116b7565b6106d688611782565b6117ca565b60208701519061135d565b6020860152610759565b84516106fd9089906117fd565b89848151811061070957fe5b602002602001018181525050610726338c8c868151811061066e57fe5b93508382848151811061073557fe5b6020026020010181815250506107536106db8b85815181106106bc57fe5b60208601525b61078389848151811061076857fe5b6020026020010151866000015161135d90919063ffffffff16565b85526040850151610794908561135d565b8560400181815250506107ba8b8b85815181106107ad57fe5b602002602001015161185a565b8184815181106107c657fe5b6020908102919091010152600190920191610617565b895183101561080a5760008984815181106107f357fe5b6020026020010181815250508260010192506107dc565b84516040516001600160a01b038d169133917f6008478fd0513693018a0ac8771ada053137941c0d833295a27629af7a3ab56b9161084d918f918f9189906156b9565b60405180910390a3604051600090339081907f4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb9061088e9086908f9061575c565b60405180910390a45050825186146108b85760405162461bcd60e51b815260040161007e906158e6565b6108cb8984600001518560400151611881565b6001600160a01b03891660009081526039602052604090819020549084015161091491339161090f916106db919063ffffffff600160401b90910481169061197d16565b6119d6565b826020015183604001519450945050505094509492505050565b600080610939610f9d565b6001600160a01b038516600090815260398201602052604090205490915060e01b7fffffffff00000000000000000000000000000000000000000000000000000000166109985760405162461bcd60e51b815260040161007e90615b7e565b6001600160a01b0384166000908152603982016020526040812054819030906109ea9088907c0100000000000000000000000000000000000000000000000000000000810460f81b9060e01b89611cac565b6040516109f7919061565b565b600060405180830381855afa9150503d8060008114610a32576040519150601f19603f3d011682016040523d82523d6000602084013e610a37565b606091505b509150915081610a54578051610a4c57600080fd5b805181602001fd5b6020015195945050505050565b60008083118015610a725750600084115b610a8e5760405162461bcd60e51b815260040161007e90615cc8565b610a99858385611dc3565b9092509050610ac433610abf84610ab9610ab28a611e1d565b889061197d565b9061135d565b611e59565b610acf858585611f91565b610ade33868387876000612051565b949350505050565b600081806020019051810190610afc91906153c5565b90505b919050565b6000806000806000806000610b18886122dd565b925092509250610b29838383612304565b919973bea0000029ad1c77d3d5d23ba2d8893db9d1efab99509097509095509350505050565b6000806000806000806000610b63886122dd565b925092509250610b748383836123fa565b73bea0000029ad1c77d3d5d23ba2d8893db9d1efab9a92995090975095509350505050565b731bea3ccd22f4ebd3d37d731ba31eeca95713716d731bea0050e63e05fbb5d8ba2f10cf5800b62244496000808080610bd187612486565b915091506000610c03610be26124a8565b610bfd610bed612547565b610bf78b87612604565b9061197d565b906126ac565b9050600080610c30610c158987612604565b8473bea0e11282e2bb5893bece110cf199501e872bad612713565b91509150610c3e88826128fe565b9550610c4a88826129ae565b604051630852cd8d60e31b81526001600160a01b038916906342966c6890610c7690899060040161582f565b600060405180830381600087803b158015610c9057600080fd5b505af1158015610ca4573d6000803e3d6000fd5b50505050610cc8610cb3612547565b610bfd610cbe6124a8565b610bf78d876128fe565b9650610cd48983612a3f565b6040517f40c10f190000000000000000000000000000000000000000000000000000000081526001600160a01b038a16906340c10f1990610d1b9030908b906004016156a0565b600060405180830381600087803b158015610d3557600080fd5b505af1158015610d49573d6000803e3d6000fd5b5050505050505050509193509193565b731bea0050e63e05fbb5d8ba2f10cf5800b6224449731bea3ccd22f4ebd3d37d731ba31eeca95713716d6000808080610d9187612486565b915091506000610dad610da2612547565b610bfd610bed6124a8565b9050600080610dda610dbf8987612604565b8473bea0e11282e2bb5893bece110cf199501e872bad612ad0565b91509150610de888826128fe565b9550610df488826129ae565b604051630852cd8d60e31b81526001600160a01b038916906342966c6890610e2090899060040161582f565b600060405180830381600087803b158015610e3a57600080fd5b505af1158015610e4e573d6000803e3d6000fd5b50505050610cc8610e5d6124a8565b610bfd610cbe612547565b600080600080610e7785612b4c565b96879650909450849350915050565b6000806000806000806000610e9a886122dd565b92509250925080965073bea0000029ad1c77d3d5d23ba2d8893db9d1efab9550610ec5838383612713565b97999698509695945050505050565b6000806000806000806000610ee8886122dd565b92509250925073bea0000029ad1c77d3d5d23ba2d8893db9d1efab9650809550610ec5838383612ad0565b600080610f1e610f9d565b6001600160a01b03841660009081526031820160205260409020600a0154909150640100000000900463ffffffff1615801590610f96575060038101546001600160a01b03841660009081526031830160205260409020600a0154600160c01b90910461ffff1664010000000090910463ffffffff16105b9392505050565b600090565b600080610fad610f9d565b6001600160a01b03939093166000908152603193909301602052505060409020600a0154640100000000900463ffffffff1690565b6000610fec610f9d565b6001600160a01b03841660009081526031820160205260409020600e01549091506110785760038101546001600160a01b038416600090815260319092016020526040909120600a0180546bffffffff00000000000000001916600160681b90920463ffffffff16600160401b02919091176fffffffff0000000000000000000000001916905561126b565b600381015463ffffffff80841669010000000000000000009092041611156110fc576110a383612b63565b6001600160a01b0384166000908152603183016020526040902060148101919091556003820154600a90910180546bffffffff0000000000000000191664010000000090920463ffffffff16600160401b029190911790555b600381015471010000000000000000000000000000000000900460ff161561120457600381015463ffffffff808416600160681b9092041611156111995760038101546001600160a01b03841660009081526031830160205260409020600a810180546fffffffff0000000000000000000000001916600160681b90930463ffffffff16600160601b0292909217909155600e8101546012909101555b6003810154640100000000810463ffffffff908116600160681b9092041614156111ff576003810154640100000000900463ffffffff166000908152603d820160209081526040808320546001600160a01b038716845260318501909252909120601301555b611269565b6001600160a01b03831660009081526031820160205260409020600a0154600160601b900463ffffffff1615611269576001600160a01b03831660009081526031820160205260409020600a0180546fffffffff000000000000000000000000191690555b505b5050565b6000611279610f9d565b90506000611286836116b7565b6001600160a01b03858116600090815260318501602090815260408083209388168352601a90930190522054909150600b81900b90600160601b90046001600160801b031680156112fc5782600b0b82600b0b14156112e8575050505061126b565b6112fc866112f7848685612d82565b612d8f565b50506001600160a01b0380851660009081526031909301602090815260408085209286168552601a90920190529091208054600b9290920b6bffffffffffffffffffffffff166bffffffffffffffffffffffff199092169190911790555050565b6000828201838110156113b7576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b90505b92915050565b6000806113cb610f9d565b905060006113d9868661185a565b6001600160a01b038816600090815260318401602090815260408083208484526019019091529020546001600160801b03600160801b82048116955091925016808511156114395760405162461bcd60e51b815260040161007e90615b10565b808510156115ca57600061145182610bfd888861197d565b9050600061145f86836117fd565b9050600061146d84896117fd565b6001600160a01b038c1660009081526031880160209081526040808320898452601901909152902080546001600160801b03858116600160801b028482166fffffffffffffffffffffffffffffffff19909316929092171617905590506115516114d684611782565b8760310160008e6001600160a01b03166001600160a01b03168152602001908152602001600020601a0160008d6001600160a01b03166001600160a01b03168152602001908152602001600020600001600c9054906101000a90046001600160801b03166001600160801b0316612ea690919063ffffffff16565b6001600160a01b03808d166000908152603190980160209081526040808a20928e168a52601a909201905290962080546001600160801b0397909716600160601b027fffffffff00000000000000000000000000000000ffffffffffffffffffffffff90971696909617909555509350610ade92505050565b80156115fa576001600160a01b038816600090815260318401602090815260408083208584526019019091528120555b6001600160a01b0388811660009081526031850160209081526040808320938b168352601a9093019052205461164090600160601b90046001600160801b031685612ea6565b6001600160a01b03808a166000908152603190950160209081526040808720928b168752601a909201905290932080546001600160801b0394909416600160601b027fffffffff00000000000000000000000000000000ffffffffffffffffffffffff909416939093179092555050949350505050565b6000806116c2610f9d565b6001600160a01b0384166000908152603982016020526040902054600382015491925061175291620f424091611749916117139163ffffffff918216600b0b91600160601b909104811690612f0f16565b6001600160a01b038716600090815260398601602052604090205463ffffffff6401000000009091048116600b0b9190612f8716565b600b0b90613057565b6001600160a01b03909316600090815260399091016020526040902054600160801b9004600b0b91909101919050565b6000600160801b82106117c65760405162461bcd60e51b8152600401808060200182810382526027815260200180615dd16027913960400191505060405180910390fd5b5090565b6000806117e8836117df600b87900b88612f0f565b600b0b90612f87565b600b0b6001600160801b031695945050505050565b600082821115611854576040805162461bcd60e51b815260206004820152601e60248201527f536166654d6174683a207375627472616374696f6e206f766572666c6f770000604482015290519081900360640190fd5b50900390565b6bffffffffffffffffffffffff1660609190911b6bffffffffffffffffffffffff19161790565b600061188b610f9d565b90506118c361189984611782565b6001600160a01b03861660009081526038840160205260409020546001600160801b031690612ea6565b6001600160a01b0385166000908152603883016020526040902080546fffffffffffffffffffffffffffffffff19166001600160801b039290921691909117905561194161191083611782565b6001600160a01b0386166000908152603884016020526040902054600160801b90046001600160801b031690612ea6565b6001600160a01b03909416600090815260389091016020526040902080546001600160801b03948516600160801b029416939093179092555050565b60008261198c575060006113ba565b8282028284828161199957fe5b04146113b75760405162461bcd60e51b8152600401808060200182810382526021815260200180615e196021913960400191505060405180910390fd5b60006119e0610f9d565b9050816119ed575061126b565b60006119f761312c565b15611aee57603c820154601b830154601d840154611a2592909186916001600160801b031690036001613165565b6001600160a01b038516600090815260318401602052604081206008810154600a909101549293509091611a6e9190610bfd90600160801b90046001600160801b03168761197d565b9050611ab0611a7c82611782565b6001600160a01b03871660009081526031860160205260409020600a0154600160801b90046001600160801b031690612ea6565b6001600160a01b03861660009081526031850160205260409020600a0180546001600160801b03928316600160801b02921691909117905550611b08565b601b820154601d830154611b059185906001613165565b90505b6001600160a01b03841660009081526031830160205260409020600e0154811115611b4d57506001600160a01b03831660009081526031820160205260409020600e01545b601b820154611b5c90846117fd565b601b8301556001600160a01b0384166000908152603183016020526040902060080154611b8990846117fd565b6001600160a01b0385166000908152603184016020526040902060080155601d820154611bb690826117fd565b601d8301556001600160a01b03841660009081526031830160205260409020600e0154611be390826117fd565b6001600160a01b03851660009081526031840160205260409020600e0155600382015471010000000000000000000000000000000000900460ff1615611c5d57601a820154611c3290826117fd565b601a8301556001600160a01b03841660009081526031830160205260409020600e8101546012909101555b836001600160a01b03167fb2d61db64b8ad7535308d2111c78934bc32baf9b7cd3a2e58cba25730003cd588460000383600003604051611c9e929190615838565b60405180910390a250505050565b60607fff000000000000000000000000000000000000000000000000000000000000008416611d4d578282604051602401611ce7919061582f565b60408051601f198184030181529190526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fffffffff00000000000000000000000000000000000000000000000000000000909316929092179091529050610ade565b7f01000000000000000000000000000000000000000000000000000000000000007fff0000000000000000000000000000000000000000000000000000000000000085161415611dab57828583604051602401611ce79291906156a0565b60405162461bcd60e51b815260040161007e90615aa2565b6000806000611dd1866116b7565b9050611df3611de8611de387876126ac565b6131ac565b600b83900b90612f0f565b9150611e0f611e01856131ac565b6117df600b84900b85612f0f565b600b0b925050935093915050565b600080611e28610f9d565b6001600160a01b0393909316600090815260399390930160205250506040902054600160401b900463ffffffff1690565b6000611e63610f9d565b601d810154909150600090611e8b57611e84611e7d6131da565b849061197d565b9050611ea7565b601b820154601d830154611ea49190610bfd908661197d565b90505b601b820154611eb6908461135d565b601b8301556001600160a01b0384166000908152603183016020526040902060080154611ee3908461135d565b6001600160a01b0385166000908152603184016020526040902060080155601d820154611f10908261135d565b601d8301556001600160a01b03841660009081526031830160205260409020600e0154611f3d908261135d565b6001600160a01b038516600081815260318501602052604090819020600e019290925590517fb2d61db64b8ad7535308d2111c78934bc32baf9b7cd3a2e58cba25730003cd5890611c9e9086908590615838565b6000611f9b610f9d565b9050611fd3611fa984611782565b6001600160a01b03861660009081526038840160205260409020546001600160801b0316906131e3565b6001600160a01b0385166000908152603883016020526040902080546fffffffffffffffffffffffffffffffff19166001600160801b039290921691909117905561194161202083611782565b6001600160a01b0386166000908152603884016020526040902054600160801b90046001600160801b0316906131e3565b600061205b610f9d565b90506000612069878761185a565b90506120af61207786611782565b6001600160a01b038a16600090815260318501602090815260408083208684526019019091529020546001600160801b0316906131e3565b6001600160a01b03891660009081526031840160209081526040808320858452601901909152902080546fffffffffffffffffffffffffffffffff19166001600160801b039290921691909117905561214961210a85611782565b6001600160a01b038a1660009081526031850160209081526040808320868452601901909152902054600160801b90046001600160801b0316906131e3565b6001600160a01b03808a166000908152603185016020908152604080832086845260198101835281842080546001600160801b03978816600160801b02908816179055938c168352601a909301905220546121ad91600160601b90910416856131e3565b6001600160a01b03808a1660009081526031850160209081526040808320938c168352601a909301905290812080546001600160801b0393909316600160601b027fffffffff00000000000000000000000000000000ffffffffffffffffffffffff9093169290921790915583600181111561222557fe5b141561228457876001600160a01b031660006001600160a01b0316336001600160a01b03167fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62848960405161227b929190615838565b60405180910390a45b866001600160a01b0316886001600160a01b03167ff4d42fc7416f300569832aee6989201c613d31d64b823327915a6a33fe7afa558888886040516122cb93929190615846565b60405180910390a35050505050505050565b6000806000838060200190518101906122f69190615452565b919790965090945092505050565b600080600061231284613249565b9050600081116123345760405162461bcd60e51b815260040161007e90615bec565b8086116123415785612343565b805b6040805180820182528281526000602082015290517f0b4c7e4d0000000000000000000000000000000000000000000000000000000081529193506001600160a01b03861691630b4c7e4d9161239d918990600401615724565b602060405180830381600087803b1580156123b757600080fd5b505af11580156123cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123ef919061556d565b925050935093915050565b6000806000612408846132ed565b90506000811161242a5760405162461bcd60e51b815260040161007e906159a0565b8086116124375785612439565b805b6040517f1a4d01d20000000000000000000000000000000000000000000000000000000081529092506001600160a01b03851690631a4d01d29061239d9085906000908a90600401615d2d565b6000808280602001905181019061249d919061541e565b909590945092505050565b6000806124b3610f9d565b90506125406124c061338e565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156124f857600080fd5b505afa15801561250c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612530919061556d565b610bfd8360480154610bf76133a6565b9150505b90565b600080612552610f9d565b905061254061255f6133ad565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561259757600080fd5b505afa1580156125ab573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125cf919061556d565b731bea0050e63e05fbb5d8ba2f10cf5800b622444960009081526040808501602052902060010154610bfd90620f424061197d565b60008061260f610f9d565b9050610ade846001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561264d57600080fd5b505afa158015612661573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612685919061556d565b6001600160a01b03861660009081526040808501602052902060010154610bfd908661197d565b6000808211612702576040805162461bcd60e51b815260206004820152601a60248201527f536166654d6174683a206469766973696f6e206279207a65726f000000000000604482015290519081900360640190fd5b81838161270b57fe5b049392505050565b600080600080612722856133c5565b91509150600082116127465760405162461bcd60e51b815260040161007e90615bec565b8187116127535786612755565b815b92506000856001600160a01b0316639d63848a6040518163ffffffff1660e01b815260040160006040518083038186803b15801561279257600080fd5b505afa1580156127a6573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526127ce9190810190615090565b90506127d861363d565b6001600160a01b031663a9059cbb878a6040518363ffffffff1660e01b81526004016128059291906156a0565b602060405180830381600087803b15801561281f57600080fd5b505af1158015612833573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061285791906152f3565b506040517fef4fcafa0000000000000000000000000000000000000000000000000000000081526001600160a01b0387169063ef4fcafa9061289f9030908b906004016156a0565b602060405180830381600087803b1580156128b957600080fd5b505af11580156128cd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128f1919061556d565b9450505050935093915050565b600080612909610f9d565b9050610ade816040016000866001600160a01b03166001600160a01b0316815260200190815260200160002060010154610bfd85876001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561297657600080fd5b505afa15801561298a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bf7919061556d565b60006129b8610f9d565b90506001600160a01b038316731bea3ccd22f4ebd3d37d731ba31eeca95713716d1415612a3557731bea3ccd22f4ebd3d37d731ba31eeca95713716d600090815260408083016020528120600101546048830154612a1c9190610bfd90869061197d565b6048830154909150612a2e90826117fd565b6048830155505b6112698383613655565b6000612a49610f9d565b90506001600160a01b038316731bea3ccd22f4ebd3d37d731ba31eeca95713716d1415612ac657731bea3ccd22f4ebd3d37d731ba31eeca95713716d600090815260408083016020528120600101546048830154612aad9190610bfd90869061197d565b6048830154909150612abf908261135d565b6048830155505b61126983836136ea565b6000806000612ade8461376f565b905060008111612b005760405162461bcd60e51b815260040161007e906159a0565b808611612b0d5785612b0f565b805b9150836001600160a01b0316635fe192c683612b2961363d565b8830426040518663ffffffff1660e01b815260040161239d959493929190615cff565b6000808280602001905181019061249d91906153df565b600080612b6e610f9d565b6001600160a01b038416600090815260318201602052604081206014810154600a82015490955092935091600160601b900463ffffffff1615612c9657600a820154600160401b810463ffffffff908116600160601b909204161415612bd957506013810154612bfe565b50600a810154600160401b900463ffffffff166000908152603d830160205260409020545b6001600160a01b03851660009081526031840160209081526040808320600a0154600160601b900463ffffffff168352603d860190915290205481811115612c90576001600160a01b03861660009081526031850160205260409020601201549091829190820390612c8c90612c859069d3c21bcecceda100000090610bfd90859061197d565b879061135d565b9550505b50612cd2565b506001600160a01b03841660009081526031830160209081526040808320600a0154600160401b900463ffffffff168352603d85019091529020545b612cdb85610fa2565b600384015463ffffffff9182166401000000009091049091161115612d7a57600383015463ffffffff64010000000090910481166000908152603d850160205260408120549091612d2f919084906117fd16565b6001600160a01b03871660009081526031860160205260409020600e0154909150612d7690612d6f9069d3c21bcecceda100000090610bfd90859061197d565b869061135d565b9450505b505050919050565b6000610ade8484846117ca565b6000612d99610f9d565b601d810154909150600090612db357611e84611e7d6131da565b601b820154601d830154612dcc9190610bfd908661197d565b9050612dd661312c565b15611ea757603c820154601b830154601d840154600092612e18926001600160801b0380831690910392610bfd928992610bf79291600160801b90041661135d565b90506000612e27838303611782565b603c850154909150612e4990600160801b90046001600160801b0316826131e3565b603c850180546001600160801b03908116600160801b9382168402179091556001600160a01b03881660009081526031870160205260409020600a01805482169390911690910291909117905550601b820154611eb6908461135d565b6000826001600160801b0316826001600160801b03161115611854576040805162461bcd60e51b815260206004820152601e60248201527f536166654d6174683a207375627472616374696f6e206f766572666c6f770000604482015290519081900360640190fd5b6000818303600b83900b8213801590612f2e575083600b0b81600b0b13155b80612f4c5750600083600b0b128015612f4c575083600b0b81600b0b135b6113b75760405162461bcd60e51b8152600401808060200182810382526024815260200180615e616024913960400191505060405180910390fd5b600082600b0b60001415612f9d575060006113ba565b82600b0b600019148015612fc15750600b82900b6b7fffffffffffffffffffffff19145b15612ffd5760405162461bcd60e51b8152600401808060200182810382526027815260200180615e3a6027913960400191505060405180910390fd5b6000828402905082600b0b84600b0b82600b0b8161301757fe5b05600b0b146113b75760405162461bcd60e51b8152600401808060200182810382526027815260200180615e3a6027913960400191505060405180910390fd5b600081600b0b600014156130b2576040805162461bcd60e51b815260206004820181905260248201527f5369676e6564536166654d6174683a206469766973696f6e206279207a65726f604482015290519081900360640190fd5b81600b0b6000191480156130d65750600b83900b6b7fffffffffffffffffffffff19145b156131125760405162461bcd60e51b8152600401808060200182810382526021815260200180615df86021913960400191505060405180910390fd5b600082600b0b84600b0b8161312357fe5b05949350505050565b600080613137610f9d565b60030154600a73010000000000000000000000000000000000000090910463ffffffff164303111592915050565b600080613173868686613b18565b9050600183600281111561318357fe5b14801561319a57506000848061319557fe5b868809115b156131a3576001015b95945050505050565b60006b7fffffffffffffffffffffff8211156117c65760405162461bcd60e51b815260040161007e90615943565b64e8d4a5100090565b60008282016001600160801b0380851690821610156113b7576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b600080826001600160a01b03166314f059796040518163ffffffff1660e01b8152600401604080518083038186803b15801561328457600080fd5b505afa158015613298573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132bc91906151f1565b905060006132ca8483613bbe565b825190915081116132e057600092505050610aff565b8151610ade9082906117fd565b600080826001600160a01b03166314f059796040518163ffffffff1660e01b8152600401604080518083038186803b15801561332857600080fd5b505afa15801561333c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061336091906151f1565b9050600061336e8483613bbe565b8251909150811061338457600092505050610aff565b610ade8282613c0d565b731bea3ccd22f4ebd3d37d731ba31eeca95713716d90565b621cc1b090565b731bea0050e63e05fbb5d8ba2f10cf5800b622444990565b6000806000836001600160a01b0316639d63848a6040518163ffffffff1660e01b815260040160006040518083038186803b15801561340357600080fd5b505afa158015613417573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261343f9190810190615090565b90506000846001600160a01b0316630902f1ac6040518163ffffffff1660e01b815260040160006040518083038186803b15801561347c57600080fd5b505afa158015613490573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526134b8919081019061526f565b90506000856001600160a01b03166310dd08306040518163ffffffff1660e01b815260040160006040518083038186803b1580156134f557600080fd5b505afa158015613509573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526135319190810190615499565b90506060600061354085613ce0565b9097509092509050806135655760405162461bcd60e51b815260040161007e90615ad9565b825160208401516040516316a1119f60e21b81526000926001600160a01b031691635a84467c9161359e9189918c9189916004016157a6565b60206040518083038186803b1580156135b657600080fd5b505afa1580156135ca573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135ee919061556d565b90508487815181106135fc57fe5b602002602001015181116136195760009750505050505050613638565b84878151811061362557fe5b6020026020010151810397505050505050505b915091565b73bea0000029ad1c77d3d5d23ba2d8893db9d1efab90565b600061365f610f9d565b6001600160a01b0384166000908152604080830160205290206001015490915061368990836117fd565b6001600160a01b0384166000818152604080850160205280822060010193909355915190917f034be0cb985c00ed623355853288b175a6c0bd25ed03d64e9895ccec774af9e7916136dd918690039061582f565b60405180910390a2505050565b60006136f4610f9d565b6001600160a01b0384166000908152604080830160205290206001015490915061371e908361135d565b6001600160a01b03841660008181526040808501602052908190206001019290925590517f034be0cb985c00ed623355853288b175a6c0bd25ed03d64e9895ccec774af9e7906136dd90859061582f565b600080826001600160a01b0316639d63848a6040518163ffffffff1660e01b815260040160006040518083038186803b1580156137ab57600080fd5b505afa1580156137bf573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526137e79190810190615090565b90506000836001600160a01b0316630902f1ac6040518163ffffffff1660e01b815260040160006040518083038186803b15801561382457600080fd5b505afa158015613838573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052613860919081019061526f565b90506000846001600160a01b03166310dd08306040518163ffffffff1660e01b815260040160006040518083038186803b15801561389d57600080fd5b505afa1580156138b1573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526138d99190810190615499565b905060008060006138e986613ce0565b9250925092508061390c5760405162461bcd60e51b815260040161007e90615ad9565b835160208501516040516316a1119f60e21b81526000926001600160a01b031691635a84467c91613945918a9188918a916004016157a6565b60206040518083038186803b15801561395d57600080fd5b505afa158015613971573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613995919061556d565b9050808684815181106139a457fe5b6020026020010151116139c1576000975050505050505050610aff565b845160208601516040517f14c15fc00000000000000000000000000000000000000000000000000000000081526000926001600160a01b0316916314c15fc091613a0f918b91600401615781565b60206040518083038186803b158015613a2757600080fd5b505afa158015613a3b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a5f919061556d565b905081878581518110613a6e57fe5b602002602001018181525050613b0a86600001516001600160a01b03166314c15fc08989602001516040518363ffffffff1660e01b8152600401613ab3929190615781565b60206040518083038186803b158015613acb57600080fd5b505afa158015613adf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613b03919061556d565b82906117fd565b9a9950505050505050505050565b6000808060001985870986860292508281109083900303905080613b4957838281613b3f57fe5b0492505050610f96565b808411613b5557600080fd5b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b60006001600160a01b03831673c9c32cd16bf7efb85ff14e0c8603cc90f6f2ee491415613bf557613bee82613e2b565b90506113ba565b60405162461bcd60e51b815260040161007e90615889565b600080613c18613ec8565b6001600160a01b03166376a2f0f06040518163ffffffff1660e01b815260040160206040518083038186803b158015613c5057600080fd5b505afa158015613c64573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613c88919061556d565b90506000613c9585613ee0565b90506000613ca38284613ef7565b90506000613cb98688835b6020020151906117fd565b9050613cc781888487614003565b9050613cd58188848761416c565b979650505050505050565b606060008060019050835167ffffffffffffffff81118015613d0157600080fd5b50604051908082528060200260200182016040528015613d2b578160200160208202803683370190505b509250600019915060005b8451811015613e0157848181518110613d4b57fe5b60200260200101516001600160a01b031673bea0000029ad1c77d3d5d23ba2d8893db9d1efab6001600160a01b03161415613da457809250620f4240848281518110613d9357fe5b602002602001018181525050613df9565b613dc0858281518110613db357fe5b602002602001015161422f565b848281518110613dcc57fe5b602002602001018181525050838181518110613de457fe5b602002602001015160001415613df957600091505b600101613d36565b50600019821415613e245760405162461bcd60e51b815260040161007e90615bb5565b9193909250565b6000610afc6c0c9f2c9cd04674edea40000000610bfd613e496142a5565b6001600160a01b031663bb7b8b806040518163ffffffff1660e01b815260040160206040518083038186803b158015613e8157600080fd5b505afa158015613e95573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613eb9919061556d565b8560015b60200201519061197d565b73c9c32cd16bf7efb85ff14e0c8603cc90f6f2ee4990565b613ee8614f12565b610afc8264e8d4a510006142bd565b6000806000805b6002811015613f2557858160028110613f1357fe5b60200201519290920191600101613efe565b5081613f36576000925050506113ba565b90915081906002840260005b610100811015613fea578460005b6002811015613f82576002898260028110613f6757fe5b60200201510287830281613f7757fe5b049150600101613f50565b508593506003810260646063198501860204018660028302606486890204010281613fa957fe5b0495508386118015613fbe5750600184870311155b15613fcd5750505050506113ba565b600186850311613fe15750505050506113ba565b50600101613f42565b5060405162461bcd60e51b815260040161007e90615c91565b60008061400f85613ee0565b90506000614026614021888884613cae565b614347565b9050600061405860405180604001604052808481526020018560016002811061404b57fe5b6020020151905286613ef7565b9050614062614f12565b600061407d846140778a610bfd878a87613ebd565b906117fd565b90506140a56402540be400614095621e84808461197d565b8161409c57fe5b04866000613cae565b82526140c26140ba89610bfd86896001613ebd565b866001613cae565b90506140ea6402540be4006140da621e84808461197d565b816140e157fe5b04866001613cae565b602083015260006140fd88828587614358565b9050600061410c828583613cae565b905061412161411c8260016117fd565b614441565b9050600061413361411c888a84613cae565b905061415b6141546402540be400610bfd64012a05f200610bf786886117fd565b829061135d565b9d9c50505050505050505050505050565b6000614179858583613cae565b8452600061418685613ee0565b905060006141948285613ef7565b905060006141a286836117fd565b905061422386610bfd6141b3613ec8565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156141eb57600080fd5b505afa1580156141ff573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e7d919061556d565b98975050505050505050565b60006001600160a01b03821673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2141561428d576000614260614452565b905080614271576000915050610aff565b61428569d3c21bcecceda1000000826126ac565b915050610aff565b60405162461bcd60e51b815260040161007e90615a6b565b73bebc44782c7db0a1a60cb6fe97d0b483032ff1c790565b6142c5614f12565b6113b783836142d26142a5565b6001600160a01b031663bb7b8b806040518163ffffffff1660e01b815260040160206040518083038186803b15801561430a57600080fd5b505afa15801561431e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614342919061556d565b614527565b6000610afc8264e8d4a5100061197d565b60008080808460028902825b60028110156143af5789811461438c5788816002811061438057fe5b60200201519450614391565b6143a7565b9484019460028502838902816143a357fe5b0492505b600101614364565b5060028102606488840202816143c157fe5b04915060008160648902816143d257fe5b048601905087965060005b60ff811015613fea57879450888289600202010384898a0201816143fd57fe5b04975084881180156144125750600185890311155b156144235750505050505050610ade565b6001888603116144395750505050505050610ade565b6001016143dd565b6000610afc8264e8d4a510006126ac565b60008061445d614561565b90508061446e576000915050612544565b6000614478614719565b905060006144868284614795565b9050660aa87bee5380008110156144b0576144a66002610bfd858561135d565b9350505050612544565b60006144ba6147d7565b905060006144c88286614795565b90508281101561450957662386f26fc100008110156144fc576144f06002610bfd878561135d565b95505050505050612544565b8495505050505050612544565b662386f26fc100008310156144fc576144f06002610bfd878761135d565b61452f614f12565b61453b83856000613ebd565b8152614555670de0b6b3a7640000610bfd84876001613ebd565b60208201529392505050565b600080735f4ec3df9cbd43714fe2740f5e3616155c5b84196001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156145b157600080fd5b505afa9250505080156145e1575060408051601f3d908101601f191682019092526145de918101906155d4565b60015b6145ef576000915050612544565b9050735f4ec3df9cbd43714fe2740f5e3616155c5b84196001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a06040518083038186803b15801561463e57600080fd5b505afa92505050801561466e575060408051601f3d908101601f1916820190925261466b91810190615585565b60015b61467c576000915050612544565b69ffffffffffffffffffff851661469c5760009650505050505050612544565b8115806146a857504282115b156146bc5760009650505050505050612544565b6138406146c942846117fd565b11156146de5760009650505050505050612544565b600084136146f55760009650505050505050612544565b61470c60ff8716600a0a610bfd86620f424061197d565b9650505050505050612544565b600080600061473e7388e6a0c2ddd26feeb64f039a2c41296fcb3f564061038461484c565b915091508161475257600092505050612544565b61478e81670de0b6b3a764000073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc273a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48614a02565b9250505090565b60006147ad82610bfd85670de0b6b3a764000061197d565b90508183116147c65780670de0b6b3a7640000036113b7565b670de0b6b3a763ffff190192915050565b60008060006147fc7311b815efb8f581194ae79006d24e0d814b7697f661038461484c565b915091508161481057600092505050612544565b61478e81670de0b6b3a764000073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc273dac17f958d2ee523a2206206994597c13d831ec7614a02565b60008063ffffffff83166148725760405162461bcd60e51b815260040161007e90615a34565b60408051600280825260608201835260009260208301908036833701905050905083816000815181106148a157fe5b602002602001019063ffffffff16908163ffffffff16815250506000816001815181106148ca57fe5b63ffffffff909216602092830291909101909101526040517f883bdbfd0000000000000000000000000000000000000000000000000000000081526001600160a01b0386169063883bdbfd906149249084906004016157e5565b60006040518083038186803b15801561493c57600080fd5b505afa92505050801561497157506040513d6000823e601f3d908101601f1916820160405261496e9190810190615129565b60015b61497a576149fa565b60008260008151811061498957fe5b60200260200101518360018151811061499e57fe5b60200260200101510390508663ffffffff168160060b816149bb57fe5b05945060008160060b1280156149e557508663ffffffff168160060b816149de57fe5b0760060b15155b156149f257600019909401935b600195505050505b509250929050565b600080614a0e86614af4565b90506001600160801b036001600160a01b03821611614a7d576001600160a01b0380821680029084811690861610614a5d57614a58600160c01b876001600160801b031683614e42565b614a75565b614a7581876001600160801b0316600160c01b614e42565b925050614aeb565b6000614a976001600160a01b03831680600160401b614e42565b9050836001600160a01b0316856001600160a01b031610614acf57614aca600160801b876001600160801b031683614e42565b614ae7565b614ae781876001600160801b0316600160801b614e42565b9250505b50949350505050565b60008060008360020b12614b0b578260020b614b13565b8260020b6000035b9050620d89e8811115614b6d576040805162461bcd60e51b815260206004820152600160248201527f5400000000000000000000000000000000000000000000000000000000000000604482015290519081900360640190fd5b600060018216614b8157600160801b614b93565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615614bc7576ffff97272373d413259a46990580e213a0260801c5b6004821615614be6576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615614c05576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615614c24576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615614c43576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615614c62576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615614c81576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615614ca1576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615614cc1576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615614ce1576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615614d01576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615614d21576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615614d41576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615614d61576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615614d81576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615614da2576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615614dc2576e5d6af8dedb81196699c329225ee6040260801c5b62040000821615614de1576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615614dfe576b048a170391f7dc42444e8fa20260801c5b60008460020b1315614e19578060001981614e1557fe5b0490505b640100000000810615614e2d576001614e30565b60005b60ff16602082901c0192505050919050565b6000808060001985870986860292508281109083900303905080614e785760008411614e6d57600080fd5b508290049050610f96565b808411614e8457600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b60405180606001604052806000815260200160008152602001600081525090565b60405180604001604052806002906020820280368337509192915050565b600082601f830112614f40578081fd5b81356020614f55614f5083615d6a565b615d46565b8281528181019085830183850287018401881015614f71578586fd5b855b85811015614f9d57813580600b0b8114614f8b578788fd5b84529284019290840190600101614f73565b5090979650505050505050565b600082601f830112614fba578081fd5b81516020614fca614f5083615d6a565b8281528181019085830183850287018401881015614fe6578586fd5b855b85811015614f9d578151614ffb81615db8565b84529284019290840190600101614fe8565b600082601f83011261501d578081fd5b8135602061502d614f5083615d6a565b8281528181019085830183850287018401881015615049578586fd5b855b85811015614f9d5781358452928401929084019060010161504b565b805160078110610aff57600080fd5b805169ffffffffffffffffffff81168114610aff57600080fd5b600060208083850312156150a2578182fd5b825167ffffffffffffffff8111156150b8578283fd5b8301601f810185136150c8578283fd5b80516150d6614f5082615d6a565b81815283810190838501858402850186018910156150f2578687fd5b8694505b8385101561511d57805161510981615db8565b8352600194909401939185019185016150f6565b50979650505050505050565b6000806040838503121561513b578081fd5b825167ffffffffffffffff80821115615152578283fd5b818501915085601f830112615165578283fd5b81516020615175614f5083615d6a565b82815281810190858301838502870184018b1015615191578788fd5b8796505b848710156151c15780518060060b81146151ad578889fd5b835260019690960195918301918301615195565b50918801519196509093505050808211156151da578283fd5b506151e785828601614faa565b9150509250929050565b600060408284031215615202578081fd5b82601f830112615210578081fd5b6040516040810181811067ffffffffffffffff8211171561522d57fe5b8060405250808385604086011115615243578384fd5b835b6002811015615264578151835260209283019290910190600101615245565b509195945050505050565b60006020808385031215615281578182fd5b825167ffffffffffffffff811115615297578283fd5b8301601f810185136152a7578283fd5b80516152b5614f5082615d6a565b81815283810190838501858402850186018910156152d1578687fd5b8694505b8385101561511d5780518352600194909401939185019185016152d5565b600060208284031215615304578081fd5b815180151581146113b7578182fd5b60008060008060608587031215615328578182fd5b843567ffffffffffffffff8082111561533f578384fd5b818701915087601f830112615352578384fd5b813581811115615360578485fd5b886020828501011115615371578485fd5b60209283019650945090860135908082111561538b578384fd5b61539788838901614f30565b935060408701359150808211156153ac578283fd5b506153b98782880161500d565b91505092959194509250565b6000602082840312156153d6578081fd5b6113b782615067565b6000806000606084860312156153f3578081fd5b6153fc84615067565b925060208401519150604084015161541381615db8565b809150509250925092565b600080600060608486031215615432578081fd5b61543b84615067565b925060208401519150604084015190509250925092565b60008060008060808587031215615467578182fd5b61547085615067565b93506020850151925060408501519150606085015161548e81615db8565b939692955090935050565b600060208083850312156154ab578182fd5b825167ffffffffffffffff808211156154c2578384fd5b90840190604082870312156154d5578384fd5b6040516040810181811083821117156154ea57fe5b60405282516154f881615db8565b8152828401518281111561550a578586fd5b80840193505086601f84011261551e578485fd5b82518281111561552a57fe5b61553c601f8201601f19168601615d46565b92508083528785828601011115615551578586fd5b61556081868501878701615d88565b5092830152509392505050565b60006020828403121561557e578081fd5b5051919050565b600080600080600060a0868803121561559c578283fd5b6155a586615076565b94506020860151935060408601519250606086015191506155c860808701615076565b90509295509295909350565b6000602082840312156155e5578081fd5b815160ff811681146113b7578182fd5b6000815180845260208085019450808401835b8381101561562457815187529582019590820190600101615608565b509495945050505050565b60008151808452615647816020860160208601615d88565b601f01601f19169290920160200192915050565b6000825161566d818460208701615d88565b9190910192915050565b6001600160a01b0394851681529290931660208301526040820152606081019190915260800190565b6001600160a01b03929092168252602082015260400190565b6080808252855190820181905260009060209060a0840190828901845b828110156156f5578151600b0b845292840192908401906001016156d6565b5050508381038285015261570981886155f5565b9150508460408401528281036060840152613cd581856155f5565b60608101818460005b600281101561574c57815183526020928301929091019060010161572d565b5050508260408301529392505050565b60006040825261576f60408301856155f5565b82810360208401526131a381856155f5565b60006040825261579460408301856155f5565b82810360208401526131a3818561562f565b6000608082526157b960808301876155f5565b85602084015282810360408401526157d181866155f5565b90508281036060840152613cd5818561562f565b6020808252825182820181905260009190848201906040850190845b8181101561582357835163ffffffff1683529284019291840191600101615801565b50909695505050505050565b90815260200190565b918252602082015260400190565b600b9390930b83526020830191909152604082015260600190565b600b9590950b8552602085019390935260408401919091526060830152608082015260a00190565b60208082526026908201527f436f6e766572743a204e6f7420612077686974656c697374656420437572766560408201527f20706f6f6c2e0000000000000000000000000000000000000000000000000000606082015260800190565b60208082526023908201527f436f6e766572743a204e6f7420656e6f75676820746f6b656e732072656d6f7660408201527f65642e0000000000000000000000000000000000000000000000000000000000606082015260800190565b60208082526027908201527f53616665436173743a2076616c756520646f65736e27742066697420696e206160408201527f6e20696e74393600000000000000000000000000000000000000000000000000606082015260800190565b60208082526017908201527f436f6e766572743a2050206d757374206265203c20312e000000000000000000604082015260600190565b60208082526029908201527f436f6e766572743a207374656d732c20616d6f756e747320617265206469666660408201527f206c656e677468732e0000000000000000000000000000000000000000000000606082015260800190565b60208082526002908201527f4250000000000000000000000000000000000000000000000000000000000000604082015260600190565b6020808252601c908201527f4f7261636c653a20546f6b656e206e6f7420737570706f727465642e00000000604082015260600190565b60208082526018908201527f53696c6f3a20496e76616c696420656e636f6465547970650000000000000000604082015260600190565b6020808252601a908201527f436f6e766572743a20555344204f7261636c65206661696c6564000000000000604082015260600190565b6020808252601c908201527f53696c6f3a2043726174652062616c616e636520746f6f206c6f772e00000000604082015260600190565b60208082526018908201527f436f6e766572743a20496e76616c6964207061796c6f61640000000000000000604082015260600190565b6020808252601b908201527f53696c6f3a20546f6b656e206e6f742077686974656c69737465640000000000604082015260600190565b60208082526011908201527f4265616e206e6f7420696e2057656c6c2e000000000000000000000000000000604082015260600190565b60208082526018908201527f436f6e766572743a2050206d757374206265203e3d20312e0000000000000000604082015260600190565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b60208082526016908201527f53696c6f3a204d6967726174696f6e206e656564656400000000000000000000604082015260600190565b60208082526018908201527f50726963653a20436f6e76657267656e63652066616c73650000000000000000604082015260600190565b6020808252601c908201527f436f6e766572743a20424456206f7220616d6f756e7420697320302e00000000604082015260600190565b9485526001600160a01b03938416602086015260408501929092529091166060830152608082015260a00190565b928352600f9190910b6020830152604082015260600190565b60405181810167ffffffffffffffff81118282101715615d6257fe5b604052919050565b600067ffffffffffffffff821115615d7e57fe5b5060209081020190565b60005b83811015615da3578181015183820152602001615d8b565b83811115615db2576000848401525b50505050565b6001600160a01b0381168114615dcd57600080fd5b5056fe53616665436173743a2076616c756520646f65736e27742066697420696e2031323820626974735369676e6564536166654d6174683a206469766973696f6e206f766572666c6f77536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f775369676e6564536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f775369676e6564536166654d6174683a207375627472616374696f6e206f766572666c6f77a264697066735822122026a7fda679202f575a92dda1c40a7dbf869828a16cb833f3839d3ec32aa699ba64736f6c63430007060033

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
Loading...
Loading
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.