Feature Tip: Add private address tag to any address under My Name Tag !
Overview
ETH Balance
0 ETH
Eth Value
$0.00More Info
Private Name Tags
ContractCreator
Multichain Info
No addresses found
Loading...
Loading
Contract Name:
ConvertGettersFacet
Compiler Version
v0.7.6+commit.7338295f
Optimization Enabled:
Yes with 100 runs
Other Settings:
default evmVersion
Contract Source Code (Solidity Standard Json-Input format)
/** * SPDX-License-Identifier: MIT **/ pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import {LibConvert} from "contracts/libraries/Convert/LibConvert.sol"; /** * @author Publius * @title ConvertGettersFacet contains view functions related to converting Deposited assets. **/ contract ConvertGettersFacet { /** * @notice Returns the maximum amount that can be converted of `tokenIn` to `tokenOut`. */ function getMaxAmountIn(address tokenIn, address tokenOut) external view returns (uint256 amountIn) { return LibConvert.getMaxAmountIn(tokenIn, tokenOut); } /** * @notice Returns the amount of `tokenOut` recieved from converting `amountIn` of `tokenIn`. */ function getAmountOut( address tokenIn, address tokenOut, uint256 amountIn ) external view returns (uint256 amountOut) { return LibConvert.getAmountOut(tokenIn, tokenOut, amountIn); } }
// 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; } }
// 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); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
// 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); } }
// 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); } }
// 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 { }
// 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; }
// 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 ); }
// 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); }
// 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); }
// 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); }
// 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 ); }
// 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++; } } }
// 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; } }
// 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]; } } }
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import "../interfaces/IDiamondCut.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; /** * @title Account * @author Publius * @notice Stores Farmer-level Beanstalk state. * @dev {Account.State} is the primary struct that is referenced from {Storage.State}. * All other structs in {Account} are referenced in {Account.State}. Each unique * Ethereum address is a Farmer. */ contract Account { /** * @notice Stores a Farmer's Plots and Pod allowances. * @param plots A Farmer's Plots. Maps from Plot index to Pod amount. * @param podAllowances An allowance mapping for Pods similar to that of the ERC-20 standard. Maps from spender address to allowance amount. */ struct Field { mapping(uint256 => uint256) plots; mapping(address => uint256) podAllowances; } /** * @notice Stores a Farmer's Deposits and Seeds per Deposit, and formerly stored Withdrawals. * @param withdrawals DEPRECATED: Silo V1 Withdrawals are no longer referenced. * @param deposits Unripe Bean/LP Deposits (previously Bean/LP Deposits). * @param depositSeeds BDV of Unripe LP Deposits / 4 (previously # of Seeds in corresponding LP Deposit). */ struct AssetSilo { mapping(uint32 => uint256) withdrawals; mapping(uint32 => uint256) deposits; mapping(uint32 => uint256) depositSeeds; } /** * @notice Represents a Deposit of a given Token in the Silo at a given Season. * @param amount The amount of Tokens in the Deposit. * @param bdv The Bean-denominated value of the total amount of Tokens in the Deposit. * @dev `amount` and `bdv` are packed as uint128 to save gas. */ struct Deposit { uint128 amount; // ───┐ 16 uint128 bdv; // ──────┘ 16 (32/32) } /** * @notice Stores a Farmer's Stalk and Seeds balances. * @param stalk Balance of the Farmer's Stalk. * @param seeds DEPRECATED – Balance of the Farmer's Seeds. Seeds are no longer referenced as of Silo V3. */ struct Silo { uint256 stalk; uint256 seeds; } /** * @notice Stores a Farmer's germinating stalk. * @param odd - stalk from assets deposited in odd seasons. * @param even - stalk from assets deposited in even seasons. */ struct FarmerGerminatingStalk { uint128 odd; uint128 even; } /** * @notice This struct stores the mow status for each Silo-able token, for each farmer. * This gets updated each time a farmer mows, or adds/removes deposits. * @param lastStem The last cumulative grown stalk per bdv index at which the farmer mowed. * @param bdv The bdv of all of a farmer's deposits of this token type. * */ struct MowStatus { int96 lastStem; // ───┐ 12 uint128 bdv; // ──────┘ 16 (28/32) } /** * @notice Stores a Farmer's Season of Plenty (SOP) balances. * @param roots The number of Roots a Farmer had when it started Raining. * @param plentyPerRoot The global Plenty Per Root index at the last time a Farmer updated their Silo. * @param plenty The balance of a Farmer's plenty. Plenty can be claimed directly for 3CRV. */ struct SeasonOfPlenty { uint256 roots; uint256 plentyPerRoot; uint256 plenty; } /** * @notice Defines the state object for a Farmer. * @param field A Farmer's Field storage. * @param bean A Farmer's Unripe Bean Deposits only as a result of Replant (previously held the V1 Silo Deposits/Withdrawals for Beans). * @param lp A Farmer's Unripe LP Deposits as a result of Replant of BEAN:ETH Uniswap v2 LP Tokens (previously held the V1 Silo Deposits/Withdrawals for BEAN:ETH Uniswap v2 LP Tokens). * @param s A Farmer's Silo storage. * @param deprecated_votedUntil DEPRECATED – Replant removed on-chain governance including the ability to vote on BIPs. * @param lastUpdate The Season in which the Farmer last updated their Silo. * @param lastSop The last Season that a SOP occured at the time the Farmer last updated their Silo. * @param lastRain The last Season that it started Raining at the time the Farmer last updated their Silo. * @param deprecated_deltaRoots DEPRECATED – BIP-39 introduced germination. * @param deprecated_lastSIs DEPRECATED – In Silo V1.2, the Silo reward mechanism was updated to no longer need to store the number of the Supply Increases at the time the Farmer last updated their Silo. * @param deprecated_proposedUntil DEPRECATED – Replant removed on-chain governance including the ability to propose BIPs. * @param deprecated_sop DEPRECATED – Replant reset the Season of Plenty mechanism * @param roots A Farmer's Root balance. * @param deprecated_wrappedBeans DEPRECATED – Replant generalized Internal Balances. Wrapped Beans are now stored at the AppStorage level. * @param legacyV2Deposits DEPRECATED - SiloV2 was retired in favor of Silo V3. A Farmer's Silo Deposits stored as a map from Token address to Season of Deposit to Deposit. * @param withdrawals Withdraws were removed in zero withdraw upgrade - A Farmer's Withdrawals from the Silo stored as a map from Token address to Season the Withdrawal becomes Claimable to Withdrawn amount of Tokens. * @param sop A Farmer's Season of Plenty storage. * @param depositAllowances A mapping of `spender => Silo token address => amount`. * @param tokenAllowances Internal balance token allowances. * @param depositPermitNonces A Farmer's current deposit permit nonce * @param tokenPermitNonces A Farmer's current token permit nonce * @param legacyV3Deposits DEPRECATED: Silo V3 deposits. Deprecated in favor of SiloV3.1 mapping from depositId to Deposit. * @param mowStatuses A mapping of Silo-able token address to MowStatus. * @param isApprovedForAll A mapping of ERC1155 operator to approved status. ERC1155 compatability. * @param farmerGerminating A Farmer's germinating stalk. Seperated into odd and even stalk. * @param deposits SiloV3.1 deposits. A mapping from depositId to Deposit. SiloV3.1 introduces greater precision for deposits. */ struct State { Field field; // A Farmer's Field storage. /* * @dev (Silo V1) A Farmer's Unripe Bean Deposits only as a result of Replant * * Previously held the V1 Silo Deposits/Withdrawals for Beans. * NOTE: While the Silo V1 format is now deprecated, this storage slot is used for gas * efficiency to store Unripe BEAN deposits. See {LibUnripeSilo} for more. */ AssetSilo bean; /* * @dev (Silo V1) Unripe LP Deposits as a result of Replant. * * Previously held the V1 Silo Deposits/Withdrawals for BEAN:ETH Uniswap v2 LP Tokens. * * BEAN:3CRV and BEAN:LUSD tokens prior to Replant were stored in the Silo V2 * format in the `s.a[account].legacyV2Deposits` mapping. * * NOTE: While the Silo V1 format is now deprecated, unmigrated Silo V1 deposits are still * stored in this storage slot. See {LibUnripeSilo} for more. * */ AssetSilo lp; /* * @dev Holds Silo specific state for each account. */ Silo s; uint32 votedUntil; // DEPRECATED – Replant removed on-chain governance including the ability to vote on BIPs. uint32 lastUpdate; // The Season in which the Farmer last updated their Silo. uint32 lastSop; // The last Season that a SOP occured at the time the Farmer last updated their Silo. uint32 lastRain; // The last Season that it started Raining at the time the Farmer last updated their Silo. uint128 deprecated_deltaRoots; // DEPRECATED - BIP-39 introduced germination. SeasonOfPlenty deprecated; // DEPRECATED – Replant reset the Season of Plenty mechanism uint256 roots; // A Farmer's Root balance. uint256 deprecated_wrappedBeans; // DEPRECATED – Replant generalized Internal Balances. Wrapped Beans are now stored at the AppStorage level. mapping(address => mapping(uint32 => Deposit)) legacyV2Deposits; // Legacy Silo V2 Deposits stored as a map from Token address to Season of Deposit to Deposit. NOTE: While the Silo V2 format is now deprecated, unmigrated Silo V2 deposits are still stored in this mapping. mapping(address => mapping(uint32 => uint256)) withdrawals; // Zero withdraw eliminates a need for withdraw mapping, but is kept for legacy SeasonOfPlenty sop; // A Farmer's Season Of Plenty storage. mapping(address => mapping(address => uint256)) depositAllowances; // Spender => Silo Token mapping(address => mapping(IERC20 => uint256)) tokenAllowances; // Token allowances uint256 depositPermitNonces; // A Farmer's current deposit permit nonce uint256 tokenPermitNonces; // A Farmer's current token permit nonce mapping(uint256 => Deposit) legacyV3Deposits; // NOTE: Legacy SiloV3 Deposits stored as a map from uint256 to Deposit. This is an concat of the token address and the CGSPBDV for a ERC20 deposit. mapping(address => MowStatus) mowStatuses; // Store a MowStatus for each Whitelisted Silo token mapping(address => bool) isApprovedForAll; // ERC1155 isApprovedForAll mapping // Germination FarmerGerminatingStalk farmerGerminating; // A Farmer's germinating stalk. // Silo v3.1 mapping(uint256 => Deposit) deposits; // Silo v3.1 Deposits stored as a map from uint256 to Deposit. This is an concat of the token address and the stem for a ERC20 deposit. } } /** * @title Storage * @author Publius * @notice Stores system-level Beanstalk state. */ contract Storage { /** * @notice DEPRECATED: System-level contract addresses. * @dev After Replant, Beanstalk stores Token addresses as constants to save gas. */ struct Contracts { address bean; address pair; address pegPair; address weth; } /** * @notice System-level Field state variables. * @param soil The number of Soil currently available. Adjusted during {Sun.stepSun}. * @param beanSown The number of Bean sown within the current Season. Reset during {Weather.calcCaseId}. * @param pods The pod index; the total number of Pods ever minted. * @param harvested The harvested index; the total number of Pods that have ever been Harvested. * @param harvestable The harvestable index; the total number of Pods that have ever been Harvestable. Included previously Harvested Beans. */ struct Field { uint128 soil; // ──────┐ 16 uint128 beanSown; // ──┘ 16 (32/32) uint256 pods; uint256 harvested; uint256 harvestable; } /** * @notice DEPRECATED: Contained data about each BIP (Beanstalk Improvement Proposal). * @dev Replant moved governance off-chain. This struct is left for future reference. * */ struct Bip { address proposer; // ───┐ 20 uint32 start; // │ 4 (24) uint32 period; // │ 4 (28) bool executed; // ──────┘ 1 (29/32) int pauseOrUnpause; uint128 timestamp; uint256 roots; uint256 endTotalRoots; } /** * @notice DEPRECATED: Contained data for the DiamondCut associated with each BIP. * @dev Replant moved governance off-chain. This struct is left for future reference. * @dev {Storage.DiamondCut} stored DiamondCut-related data for each {Bip}. */ struct DiamondCut { IDiamondCut.FacetCut[] diamondCut; address initAddress; bytes initData; } /** * @notice DEPRECATED: Contained all governance-related data, including a list of BIPs, votes for each BIP, and the DiamondCut needed to execute each BIP. * @dev Replant moved governance off-chain. This struct is left for future reference. * @dev {Storage.Governance} stored all BIPs and Farmer voting information. */ struct Governance { uint32[] activeBips; uint32 bipIndex; mapping(uint32 => DiamondCut) diamondCuts; mapping(uint32 => mapping(address => bool)) voted; mapping(uint32 => Bip) bips; } /** * @notice System-level Silo state; contains deposit and withdrawal data for a particular whitelisted Token. * @param deposited The total amount of this Token currently Deposited in the Silo. * @param depositedBdv The total bdv of this Token currently Deposited in the Silo. * @param withdrawn The total amount of this Token currently Withdrawn From the Silo. * @dev {Storage.State} contains a mapping from Token address => AssetSilo. * Currently, the bdv of deposits are asynchronous, and require an on-chain transaction to update. * Thus, the total bdv of deposits cannot be calculated, and must be stored and updated upon a bdv change. * * * Note that "Withdrawn" refers to the amount of Tokens that have been Withdrawn * but not yet Claimed. This will be removed in a future BIP. */ struct AssetSilo { uint128 deposited; uint128 depositedBdv; uint256 withdrawn; } /** * @notice Whitelist Status a token that has been Whitelisted before. * @param token the address of the token. * @param a whether the address is whitelisted. * @param isWhitelistedLp whether the address is a whitelisted LP token. * @param isWhitelistedWell whether the address is a whitelisted Well token. */ struct WhitelistStatus { address token; bool isWhitelisted; bool isWhitelistedLp; bool isWhitelistedWell; } /** * @notice System-level Silo state variables. * @param stalk The total amount of active Stalk (including Earned Stalk, excluding Grown Stalk). * @param deprecated_seeds DEPRECATED: The total amount of active Seeds (excluding Earned Seeds). * @dev seeds are no longer used internally. Balance is wiped to 0 from the mayflower update. see {mowAndMigrate}. * @param roots The total amount of Roots. */ struct Silo { uint256 stalk; uint256 deprecated_seeds; uint256 roots; } /** * @notice System-level Curve Metapool Oracle state variables. * @param initialized True if the Oracle has been initialzed. It needs to be initialized on Deployment and re-initialized each Unpause. * @param startSeason The Season the Oracle started minting. Used to ramp up delta b when oracle is first added. * @param balances The cumulative reserve balances of the pool at the start of the Season (used for computing time weighted average delta b). * @param timestamp DEPRECATED: The timestamp of the start of the current Season. `LibCurveMinting` now uses `s.season.timestamp` instead of storing its own for gas efficiency purposes. * @dev Currently refers to the time weighted average deltaB calculated from the BEAN:3CRV pool. */ struct CurveMetapoolOracle { bool initialized; // ────┐ 1 uint32 startSeason; // ──┘ 4 (5/32) uint256[2] balances; uint256 timestamp; } /** * @notice System-level Rain balances. Rain occurs when P > 1 and the Pod Rate Excessively Low. * @dev The `raining` storage variable is stored in the Season section for a gas efficient read operation. * @param deprecated Previously held Rain start and Rain status variables. Now moved to Season struct for gas efficiency. * @param pods The number of Pods when it last started Raining. * @param roots The number of Roots when it last started Raining. */ struct Rain { uint256 deprecated; uint256 pods; uint256 roots; } /** * @notice System-level Season state variables. * @param current The current Season in Beanstalk. * @param lastSop The Season in which the most recent consecutive series of Seasons of Plenty started. * @param withdrawSeasons The number of Seasons required to Withdraw a Deposit. * @param lastSopSeason The Season in which the most recent consecutive series of Seasons of Plenty ended. * @param rainStart Stores the most recent Season in which Rain started. * @param raining True if it is Raining (P > 1, Pod Rate Excessively Low). * @param fertilizing True if Beanstalk has Fertilizer left to be paid off. * @param sunriseBlock The block of the start of the current Season. * @param abovePeg Boolean indicating whether the previous Season was above or below peg. * @param stemStartSeason // season in which the stem storage method was introduced. * @param stemScaleSeason // season in which the stem v1.1 was introduced, where stems are not truncated anymore. * @param beanEthStartMintingSeason // Season to start minting in Bean:Eth pool after migrating liquidity out of the pool to protect against Pump failure. * This allows for greater precision of stems, and requires a soft migration (see {LibTokenSilo.removeDepositFromAccount}) * @param start The timestamp of the Beanstalk deployment rounded down to the nearest hour. * @param period The length of each season in Beanstalk in seconds. * @param timestamp The timestamp of the start of the current Season. */ struct Season { uint32 current; // ─────────────────┐ 4 uint32 lastSop; // │ 4 (8) uint8 withdrawSeasons; // │ 1 (9) uint32 lastSopSeason; // │ 4 (13) uint32 rainStart; // │ 4 (17) bool raining; // │ 1 (18) bool fertilizing; // │ 1 (19) uint32 sunriseBlock; // │ 4 (23) bool abovePeg; // | 1 (24) uint16 stemStartSeason; // | 2 (26) uint16 stemScaleSeason; // | 2 (28/32) uint32 beanEthStartMintingSeason; //┘ 4 (32/32) NOTE: Reset and delete after Bean:wStEth migration has been completed. uint256 start; uint256 period; uint256 timestamp; } /** * @notice System-level Weather state variables. * @param deprecated 2 slots that were previously used. * @param lastDSoil Delta Soil; the number of Soil purchased last Season. * @param lastSowTime The number of seconds it for Soil to sell out last Season. * @param thisSowTime The number of seconds it for Soil to sell out this Season. * @param t The Temperature; the maximum interest rate during the current Season for sowing Beans in Soil. Adjusted each Season. */ struct Weather { uint256[2] deprecated; uint128 lastDSoil; // ───┐ 16 (16) uint32 lastSowTime; // │ 4 (20) uint32 thisSowTime; // │ 4 (24) uint32 t; // ─────────────┘ 4 (28/32) } /** * @notice Describes a Fundraiser. * @param payee The address to be paid after the Fundraiser has been fully funded. * @param token The token address that used to raise funds for the Fundraiser. * @param total The total number of Tokens that need to be raised to complete the Fundraiser. * @param remaining The remaining number of Tokens that need to to complete the Fundraiser. * @param start The timestamp at which the Fundraiser started (Fundraisers cannot be started and funded in the same block). */ struct Fundraiser { address payee; address token; uint256 total; uint256 remaining; uint256 start; } /** * @notice Describes the settings for each Token that is Whitelisted in the Silo. * @param selector The encoded BDV function selector for the token that pertains to * an external view Beanstalk function with the following signature: * ``` * function tokenToBdv(uint256 amount) external view returns (uint256); * ``` * It is called by `LibTokenSilo` through the use of `delegatecall` * to calculate a token's BDV at the time of Deposit. * @param stalkEarnedPerSeason represents how much Stalk one BDV of the underlying deposited token * grows each season. In the past, this was represented by seeds. This is stored as 1e6, plus stalk is stored * as 1e10, so 1 legacy seed would be 1e6 * 1e10. * @param stalkIssuedPerBdv The Stalk Per BDV that the Silo grants in exchange for Depositing this Token. * previously called stalk. * @param milestoneSeason The last season in which the stalkEarnedPerSeason for this token was updated. * @param milestoneStem The cumulative amount of grown stalk per BDV for this token at the last stalkEarnedPerSeason update. * @param encodeType determine the encoding type of the selector. * a encodeType of 0x00 means the selector takes an input amount. * 0x01 means the selector takes an input amount and a token. * @param gpSelector The encoded gaugePoint function selector for the token that pertains to * an external view Beanstalk function with the following signature: * ``` * function gaugePoints( * uint256 currentGaugePoints, * uint256 optimalPercentDepositedBdv, * uint256 percentOfDepositedBdv * ) external view returns (uint256); * ``` * @param lwSelector The encoded liquidityWeight function selector for the token that pertains to * an external view Beanstalk function with the following signature `function liquidityWeight()` * @param optimalPercentDepositedBdv The target percentage of the total LP deposited BDV for this token. 6 decimal precision. * @param gaugePoints the amount of Gauge points this LP token has in the LP Gauge. Only used for LP whitelisted assets. * GaugePoints has 18 decimal point precision (1 Gauge point = 1e18). * @dev A Token is considered Whitelisted if there exists a non-zero {SiloSettings} selector. */ struct SiloSettings { bytes4 selector; // ────────────────────┐ 4 uint32 stalkEarnedPerSeason; // │ 4 (8) uint32 stalkIssuedPerBdv; // │ 4 (12) uint32 milestoneSeason; // │ 4 (16) int96 milestoneStem; // │ 12 (28) bytes1 encodeType; // │ 1 (29) int24 deltaStalkEarnedPerSeason; // ────┘ 3 (32) bytes4 gpSelector; // ────────────────┐ 4 bytes4 lwSelector; // │ 4 (8) uint128 gaugePoints; // │ 16 (24) uint64 optimalPercentDepositedBdv; // ──┘ 8 (32) } /** * @notice Describes the settings for each Unripe Token in Beanstalk. * @param underlyingToken The address of the Token underlying the Unripe Token. * @param balanceOfUnderlying The number of Tokens underlying the Unripe Tokens (redemption pool). * @param merkleRoot The Merkle Root used to validate a claim of Unripe Tokens. * @dev An Unripe Token is a vesting Token that is redeemable for a a pro rata share * of the `balanceOfUnderlying`, subject to a penalty based on the percent of * Unfertilized Beans paid back. * * There were two Unripe Tokens added at Replant: * - Unripe Bean, with its `underlyingToken` as BEAN; * - Unripe LP, with its `underlyingToken` as BEAN:3CRV LP. * * Unripe Tokens are initially distributed through the use of a `merkleRoot`. * * The existence of a non-zero {UnripeSettings} implies that a Token is an Unripe Token. */ struct UnripeSettings { address underlyingToken; uint256 balanceOfUnderlying; bytes32 merkleRoot; } /** * @notice System level variables used in the seed Gauge System. * @param averageGrownStalkPerBdvPerSeason The average Grown Stalk Per BDV * that beanstalk issues each season. * @param beanToMaxLpGpPerBdvRatio a scalar of the gauge points(GP) per bdv * issued to the largest LP share and Bean. 6 decimal precision. * @dev a beanToMaxLpGpPerBdvRatio of 0 means LP should be incentivized the most, * and that beans will have the minimum seeds ratio. see {LibGauge.getBeanToMaxLpGpPerBdvRatioScaled} */ struct SeedGauge { uint128 averageGrownStalkPerBdvPerSeason; uint128 beanToMaxLpGpPerBdvRatio; } /** * @notice Stores the twaReserves for each well during the sunrise function. */ struct TwaReserves { uint128 reserve0; uint128 reserve1; } /** * @notice Stores the total germination amounts for each whitelisted token. */ struct Deposited { uint128 amount; uint128 bdv; } /** * @notice Stores the system level germination data. */ struct TotalGerminating { mapping(address => Deposited) deposited; } struct Sr { uint128 stalk; uint128 roots; } } /** * @title AppStorage * @author Publius * @notice Defines the state object for Beanstalk. * @param deprecated_index DEPRECATED: Was the index of the BEAN token in the BEAN:ETH Uniswap V2 pool. * @param deprecated_cases DEPRECATED: The 24 Weather cases used in cases V1 (array has 32 items, but caseId = 3 (mod 4) are not cases) * @param paused True if Beanstalk is Paused. * @param pausedAt The timestamp at which Beanstalk was last paused. * @param season Storage.Season * @param c Storage.Contracts * @param f Storage.Field * @param g Storage.Governance * @param co Storage.CurveMetapoolOracle * @param r Storage.Rain * @param s Storage.Silo * @param reentrantStatus An intra-transaction state variable to protect against reentrance. * @param w Storage.Weather * @param earnedBeans The number of Beans distributed to the Silo that have not yet been Deposited as a result of the Earn function being called. * @param deprecated DEPRECATED - 14 slots that used to store state variables which have been deprecated through various updates. Storage slots can be left alone or reused. * @param a mapping (address => Account.State) * @param deprecated_bip0Start DEPRECATED - bip0Start was used to aid in a migration that occured alongside BIP-0. * @param deprecated_hotFix3Start DEPRECATED - hotFix3Start was used to aid in a migration that occured alongside HOTFIX-3. * @param fundraisers A mapping from Fundraiser ID to Storage.Fundraiser. * @param fundraiserIndex The number of Fundraisers that have occured. * @param deprecated_isBudget DEPRECATED - Budget Facet was removed in BIP-14. * @param podListings A mapping from Plot Index to the hash of the Pod Listing. * @param podOrders A mapping from the hash of a Pod Order to the amount of Pods that the Pod Order is still willing to buy. * @param siloBalances A mapping from Token address to Silo Balance storage (amount deposited and withdrawn). * @param ss A mapping from Token address to Silo Settings for each Whitelisted Token. If a non-zero storage exists, a Token is whitelisted. * @param deprecated2 DEPRECATED - 2 slots that used to store state variables which have been deprecated through various updates. Storage slots can be left alone or reused. * @param deprecated_newEarnedStalk the amount of earned stalk issued this season. Since 1 stalk = 1 bean, it represents the earned beans as well. * @param sops A mapping from Season to Plenty Per Root (PPR) in that Season. Plenty Per Root is 0 if a Season of Plenty did not occur. * @param internalTokenBalance A mapping from Farmer address to Token address to Internal Balance. It stores the amount of the Token that the Farmer has stored as an Internal Balance in Beanstalk. * @param unripeClaimed True if a Farmer has Claimed an Unripe Token. A mapping from Farmer to Unripe Token to its Claim status. * @param u Unripe Settings for a given Token address. The existence of a non-zero Unripe Settings implies that the token is an Unripe Token. The mapping is from Token address to Unripe Settings. * @param fertilizer A mapping from Fertilizer Id to the supply of Fertilizer for each Id. * @param nextFid A linked list of Fertilizer Ids ordered by Id number. Fertilizer Id is the Beans Per Fertilzer level at which the Fertilizer no longer receives Beans. Sort in order by which Fertilizer Id expires next. * @param activeFertilizer The number of active Fertilizer. * @param fertilizedIndex The total number of Fertilizer Beans. * @param unfertilizedIndex The total number of Unfertilized Beans ever. * @param fFirst The lowest active Fertilizer Id (start of linked list that is stored by nextFid). * @param fLast The highest active Fertilizer Id (end of linked list that is stored by nextFid). * @param bpf The cumulative Beans Per Fertilizer (bfp) minted over all Season. * @param deprecated_vestingPeriodRoots deprecated - removed in BIP-39 in favor of germination. * @param recapitalized The number of USDC that has been recapitalized in the Barn Raise. * @param isFarm Stores whether the function is wrapped in the `farm` function (1 if not, 2 if it is). * @param ownerCandidate Stores a candidate address to transfer ownership to. The owner must claim the ownership transfer. * @param wellOracleSnapshots A mapping from Well Oracle address to the Well Oracle Snapshot. * @param deprecated_beanEthPrice DEPRECATED - The price of bean:eth, originally used to calculate the incentive reward. Deprecated in favor of calculating using twaReserves. * @param twaReserves A mapping from well to its twaReserves. Stores twaReserves during the sunrise function. Returns 1 otherwise for each asset. Currently supports 2 token wells. * @param migratedBdvs Stores the total migrated BDV since the implementation of the migrated BDV counter. See {LibLegacyTokenSilo.incrementMigratedBdv} for more info. * @param usdEthPrice Stores the usdEthPrice during the sunrise() function. Returns 1 otherwise. * @param seedGauge Stores the seedGauge. * @param casesV2 Stores the 144 Weather and seedGauge cases. * @param oddGerminating Stores germinating data during odd seasons. * @param evenGerminating Stores germinating data during even seasons. * @param whitelistedStatues Stores a list of Whitelist Statues for all tokens that have been Whitelisted and have not had their Whitelist Status manually removed. * @param sopWell Stores the well that will be used upon a SOP. Unintialized until a SOP occurs, and is kept constant afterwards. * @param barnRaiseWell Stores the well that the Barn Raise adds liquidity to. */ struct AppStorage { uint8 deprecated_index; int8[32] deprecated_cases; bool paused; // ────────┐ 1 uint128 pausedAt; // ───┘ 16 (17/32) Storage.Season season; Storage.Contracts c; Storage.Field f; Storage.Governance g; Storage.CurveMetapoolOracle co; Storage.Rain r; Storage.Silo s; uint256 reentrantStatus; Storage.Weather w; uint256 earnedBeans; uint256[14] deprecated; mapping (address => Account.State) a; uint32 deprecated_bip0Start; // ─────┐ 4 uint32 deprecated_hotFix3Start; // ──┘ 4 (8/32) mapping (uint32 => Storage.Fundraiser) fundraisers; uint32 fundraiserIndex; // 4 (4/32) mapping (address => bool) deprecated_isBudget; mapping(uint256 => bytes32) podListings; mapping(bytes32 => uint256) podOrders; mapping(address => Storage.AssetSilo) siloBalances; mapping(address => Storage.SiloSettings) ss; uint256[2] deprecated2; uint128 deprecated_newEarnedStalk; // ──────┐ 16 uint128 deprecated_vestingPeriodRoots; // ──┘ 16 (32/32) mapping (uint32 => uint256) sops; // Internal Balances mapping(address => mapping(IERC20 => uint256)) internalTokenBalance; // Unripe mapping(address => mapping(address => bool)) unripeClaimed; mapping(address => Storage.UnripeSettings) u; // Fertilizer mapping(uint128 => uint256) fertilizer; mapping(uint128 => uint128) nextFid; uint256 activeFertilizer; uint256 fertilizedIndex; uint256 unfertilizedIndex; uint128 fFirst; uint128 fLast; uint128 bpf; uint256 recapitalized; // Farm uint256 isFarm; // Ownership address ownerCandidate; // Well mapping(address => bytes) wellOracleSnapshots; uint256 deprecated_beanEthPrice; // Silo V3 BDV Migration mapping(address => uint256) migratedBdvs; // Well/Curve + USD Price Oracle mapping(address => Storage.TwaReserves) twaReserves; mapping(address => uint256) usdTokenPrice; // Seed Gauge Storage.SeedGauge seedGauge; bytes32[144] casesV2; // Germination Storage.TotalGerminating oddGerminating; Storage.TotalGerminating evenGerminating; // mapping from season => unclaimed germinating stalk and roots mapping(uint32 => Storage.Sr) unclaimedGerminating; Storage.WhitelistStatus[] whitelistStatuses; address sopWell; }
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import "./interfaces/IBean.sol"; import "./interfaces/ICurve.sol"; import "./interfaces/IFertilizer.sol"; import "./interfaces/IProxyAdmin.sol"; import "./libraries/Decimal.sol"; /** * @title C * @author Publius * @notice Contains constants used throughout Beanstalk. */ library C { using Decimal for Decimal.D256; using SafeMath for uint256; //////////////////// Globals //////////////////// uint256 internal constant PRECISION = 1e18; uint256 private constant CHAIN_ID = 1; bytes constant BYTES_ZERO = new bytes(0); /// @dev The block time for the chain in seconds. uint256 internal constant BLOCK_LENGTH_SECONDS = 12; //////////////////// Season //////////////////// /// @dev The length of a Season meaured in seconds. uint256 private constant CURRENT_SEASON_PERIOD = 3600; // 1 hour uint256 internal constant SOP_PRECISION = 1e24; //////////////////// Silo //////////////////// uint256 internal constant SEEDS_PER_BEAN = 2; uint256 internal constant STALK_PER_BEAN = 10000; uint256 private constant ROOTS_BASE = 1e12; //////////////////// Exploit Migration //////////////////// uint256 private constant UNRIPE_LP_PER_DOLLAR = 1884592; // 145_113_507_403_282 / 77_000_000 uint256 private constant ADD_LP_RATIO = 866616; uint256 private constant INITIAL_HAIRCUT = 185564685220298701; //////////////////// Contracts //////////////////// address internal constant BEAN = 0xBEA0000029AD1c77D3d5D23Ba2D8893dB9d1Efab; address internal constant CURVE_BEAN_METAPOOL = 0xc9C32cd16Bf7eFB85Ff14e0c8603cc90F6F2eE49; address internal constant UNRIPE_BEAN = 0x1BEA0050E63e05FBb5D8BA2f10cf5800B6224449; address internal constant UNRIPE_LP = 0x1BEA3CcD22F4EBd3d37d731BA31Eeca95713716D; address private constant CURVE_3_POOL = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; address private constant THREE_CRV = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; address private constant FERTILIZER = 0x402c84De2Ce49aF88f5e2eF3710ff89bFED36cB6; address private constant FERTILIZER_ADMIN = 0xfECB01359263C12Aa9eD838F878A596F0064aa6e; address private constant TRI_CRYPTO = 0xc4AD29ba4B3c580e6D59105FFf484999997675Ff; address private constant TRI_CRYPTO_POOL = 0xD51a44d3FaE010294C616388b506AcdA1bfAAE46; address private constant CURVE_ZAP = 0xA79828DF1850E8a3A3064576f380D90aECDD3359; address private constant UNRIPE_CURVE_BEAN_LUSD_POOL = 0xD652c40fBb3f06d6B58Cb9aa9CFF063eE63d465D; address private constant UNRIPE_CURVE_BEAN_METAPOOL = 0x3a70DfA7d2262988064A2D051dd47521E43c9BdD; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address internal constant WSTETH = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0; // Use external contract for block.basefee as to avoid upgrading existing contracts to solidity v8 address private constant BASE_FEE_CONTRACT = 0x84292919cB64b590C0131550483707E43Ef223aC; //////////////////// Well //////////////////// uint256 internal constant WELL_MINIMUM_BEAN_BALANCE = 1000_000_000; // 1,000 Beans address internal constant BEAN_ETH_WELL = 0xBEA0e11282e2bB5893bEcE110cF199501e872bAd; address internal constant BEAN_WSTETH_WELL = 0xBeA0000113B0d182f4064C86B71c315389E4715D; // The index of the Bean and Weth token addresses in all BEAN/ETH Wells. uint256 internal constant BEAN_INDEX = 0; uint256 internal constant ETH_INDEX = 1; function getSeasonPeriod() internal pure returns (uint256) { return CURRENT_SEASON_PERIOD; } function getBlockLengthSeconds() internal pure returns (uint256) { return BLOCK_LENGTH_SECONDS; } function getChainId() internal pure returns (uint256) { return CHAIN_ID; } function getSeedsPerBean() internal pure returns (uint256) { return SEEDS_PER_BEAN; } function getStalkPerBean() internal pure returns (uint256) { return STALK_PER_BEAN; } function getRootsBase() internal pure returns (uint256) { return ROOTS_BASE; } /** * @dev The pre-exploit BEAN:3CRV Curve metapool address. */ function unripeLPPool1() internal pure returns (address) { return UNRIPE_CURVE_BEAN_METAPOOL; } /** * @dev The pre-exploit BEAN:LUSD Curve plain pool address. */ function unripeLPPool2() internal pure returns (address) { return UNRIPE_CURVE_BEAN_LUSD_POOL; } function unripeBean() internal pure returns (IERC20) { return IERC20(UNRIPE_BEAN); } function unripeLP() internal pure returns (IERC20) { return IERC20(UNRIPE_LP); } function bean() internal pure returns (IBean) { return IBean(BEAN); } function usdc() internal pure returns (IERC20) { return IERC20(USDC); } function curveMetapool() internal pure returns (ICurvePool) { return ICurvePool(CURVE_BEAN_METAPOOL); } function curve3Pool() internal pure returns (I3Curve) { return I3Curve(CURVE_3_POOL); } function curveZap() internal pure returns (ICurveZap) { return ICurveZap(CURVE_ZAP); } function curveZapAddress() internal pure returns (address) { return CURVE_ZAP; } function curve3PoolAddress() internal pure returns (address) { return CURVE_3_POOL; } function threeCrv() internal pure returns (IERC20) { return IERC20(THREE_CRV); } function fertilizer() internal pure returns (IFertilizer) { return IFertilizer(FERTILIZER); } function fertilizerAddress() internal pure returns (address) { return FERTILIZER; } function fertilizerAdmin() internal pure returns (IProxyAdmin) { return IProxyAdmin(FERTILIZER_ADMIN); } function triCryptoPoolAddress() internal pure returns (address) { return TRI_CRYPTO_POOL; } function triCrypto() internal pure returns (IERC20) { return IERC20(TRI_CRYPTO); } function unripeLPPerDollar() internal pure returns (uint256) { return UNRIPE_LP_PER_DOLLAR; } function dollarPerUnripeLP() internal pure returns (uint256) { return 1e12/UNRIPE_LP_PER_DOLLAR; } function exploitAddLPRatio() internal pure returns (uint256) { return ADD_LP_RATIO; } function precision() internal pure returns (uint256) { return PRECISION; } function initialRecap() internal pure returns (uint256) { return INITIAL_HAIRCUT; } }
// 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); }
// 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); }
// 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); }
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; /** * @title ICumulativePump * @notice Provides an interface for Pumps which calculate time-weighted average * reserves through the use of a cumulative reserve. */ interface ICumulativePump { /** * @notice Reads the current cumulative reserves from the Pump * @param well The address of the Well * @param data data specific to the Well * @return cumulativeReserves The cumulative reserves from the Pump */ function readCumulativeReserves( address well, bytes memory data ) external view returns (bytes memory cumulativeReserves); /** * @notice Reads the current cumulative reserves from the Pump * @param well The address of the Well * @param startCumulativeReserves The cumulative reserves to start the TWA from * @param startTimestamp The timestamp to start the TWA from * @param data data specific to the Well * @return twaReserves The time weighted average reserves from start timestamp to now * @return cumulativeReserves The current cumulative reserves from the Pump at the current timestamp */ function readTwaReserves( address well, bytes calldata startCumulativeReserves, uint startTimestamp, bytes memory data ) external view returns (uint[] memory twaReserves, bytes memory cumulativeReserves); }
// 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 ); }
// 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); }
// 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; }
// 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); }
// SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity =0.7.6; // A loupe is a small magnifying glass used to look at diamonds. // These functions look at diamonds interface IDiamondLoupe { /// These functions are expected to be called frequently /// by tools. struct Facet { address facetAddress; bytes4[] functionSelectors; } /// @notice Gets all facet addresses and their four byte function selectors. /// @return facets_ Facet function facets() external view returns (Facet[] memory facets_); /// @notice Gets all the function selectors supported by a specific facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_); /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view returns (address[] memory facetAddresses_); /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_); }
// SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity =0.7.6; interface IERC165 { /// @notice Query if a contract implements an interface /// @param interfaceId The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceId) external view returns (bool); }
// 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); }
// SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity =0.7.6; interface IProxyAdmin { function upgrade(address proxy, address implementation) external; }
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import {LibConvertData} from "./LibConvertData.sol"; import {LibChop} from "contracts/libraries/LibChop.sol"; import {LibUnripe} from "contracts/libraries/LibUnripe.sol"; import {C} from "contracts/C.sol"; import {IBean} from "contracts/interfaces/IBean.sol"; /** * @title LibChopConvert * @author deadmanwalking */ library LibChopConvert { using LibConvertData for bytes; /** * @notice Converts Deposited Unripe tokens into their Deposited Ripe Tokens. * @param convertData The encoded data containing the info for the convert. * @return tokenOut The address of the Ripe Token received after the Convert. * @return tokenIn The address of the Unripe Token to be converted. * @return amountOut The amount of Ripe Tokens received after the Convert. * @return amountIn The amount of Unripe Tokens to be converted. */ function convertUnripeToRipe(bytes memory convertData) internal returns ( address tokenOut, address tokenIn, uint256 amountOut, uint256 amountIn ) { // Decode convertdata (amountIn, tokenIn) = convertData.lambdaConvert(); (tokenOut, amountOut) = LibChop.chop( tokenIn, amountIn, IBean(tokenIn).totalSupply() ); IBean(tokenIn).burn(amountIn); } /** * @notice Returns the final amount of ripe assets converted from its unripe counterpart * @param tokenIn The address of the unripe token converted * @param amountIn The amount of the unripe asset converted */ function getConvertedUnderlyingOut(address tokenIn, uint256 amountIn) internal view returns(uint256 amount) { // tokenIn == unripe bean address amount = LibUnripe.getPenalizedUnderlying( tokenIn, amountIn, IBean(tokenIn).totalSupply() ); } }
// 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 {LibChopConvert} from "./LibChopConvert.sol"; import {LibWell} from "contracts/libraries/Well/LibWell.sol"; import {LibBarnRaise} from "contracts/libraries/LibBarnRaise.sol"; import {C} from "contracts/C.sol"; /** * @title LibConvert * @author Publius, deadmanwalking */ library LibConvert { using SafeMath for uint256; using LibConvertData for bytes; using LibWell for address; struct convertParams { address toToken; address fromToken; uint256 fromAmount; uint256 toAmount; address account; bool decreaseBDV; } /** * @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 * note account and decreaseBDV variables are initialized at the start * as address(0) and false respectively and remain that way if a convert is not anti-lambda-lambda * If it is anti-lambda, account is the address of the account to update the deposit * and decreaseBDV is true */ function convert(bytes calldata convertData) external returns (convertParams memory cp) { LibConvertData.ConvertKind kind = convertData.convertKind(); if (kind == LibConvertData.ConvertKind.BEANS_TO_WELL_LP) { (cp.toToken, cp.fromToken, cp.toAmount, cp.fromAmount) = LibWellConvert .convertBeansToLP(convertData); } else if (kind == LibConvertData.ConvertKind.WELL_LP_TO_BEANS) { (cp.toToken, cp.fromToken, cp.toAmount, cp.fromAmount) = LibWellConvert .convertLPToBeans(convertData); } else if (kind == LibConvertData.ConvertKind.UNRIPE_BEANS_TO_UNRIPE_LP) { (cp.toToken, cp.fromToken, cp.toAmount, cp.fromAmount) = LibUnripeConvert .convertBeansToLP(convertData); } else if (kind == LibConvertData.ConvertKind.UNRIPE_LP_TO_UNRIPE_BEANS) { (cp.toToken, cp.fromToken, cp.toAmount, cp.fromAmount) = LibUnripeConvert .convertLPToBeans(convertData); } else if (kind == LibConvertData.ConvertKind.UNRIPE_TO_RIPE) { (cp.toToken, cp.fromToken, cp.toAmount, cp.fromAmount) = LibChopConvert .convertUnripeToRipe(convertData); } else if (kind == LibConvertData.ConvertKind.LAMBDA_LAMBDA) { (cp.toToken, cp.fromToken, cp.toAmount, cp.fromAmount) = LibLambdaConvert .convert(convertData); } else if (kind == LibConvertData.ConvertKind.ANTI_LAMBDA_LAMBDA) { (cp.toToken, cp.fromToken, cp.toAmount, cp.fromAmount, cp.account, cp.decreaseBDV) = LibLambdaConvert .antiConvert(convertData); } else if (kind == LibConvertData.ConvertKind.CURVE_LP_TO_BEANS) { (cp.toToken, cp.fromToken, cp.toAmount, cp.fromAmount) = LibCurveConvert .convertLPToBeans(convertData); } else { revert("Convert: Invalid payload"); } } function getMaxAmountIn(address fromToken, address toToken) internal view returns (uint256) { /// BEAN:3CRV LP -> BEAN if (fromToken == C.CURVE_BEAN_METAPOOL && toToken == C.BEAN) return LibCurveConvert.lpToPeg(C.CURVE_BEAN_METAPOOL); /// BEAN -> BEAN:3CRV LP // NOTE: cannot convert due to bean:3crv dewhitelisting // if (fromToken == C.BEAN && toToken == C.CURVE_BEAN_METAPOOL) // return LibCurveConvert.beansToPeg(C.CURVE_BEAN_METAPOOL); // Lambda -> Lambda & // Anti-Lambda -> Lambda if (fromToken == toToken) return type(uint256).max; // Bean -> Well LP Token if (fromToken == C.BEAN && toToken.isWell()) return LibWellConvert.beansToPeg(toToken); // Well LP Token -> Bean if (fromToken.isWell() && toToken == C.BEAN) return LibWellConvert.lpToPeg(fromToken); // urLP Convert if (fromToken == C.UNRIPE_LP){ // UrBEANETH -> urBEAN if (toToken == C.UNRIPE_BEAN) return LibUnripeConvert.lpToPeg(); // UrBEANETH -> BEANETH if (toToken == LibBarnRaise.getBarnRaiseWell()) return type(uint256).max; } // urBEAN Convert if (fromToken == C.UNRIPE_BEAN){ // urBEAN -> urLP if (toToken == C.UNRIPE_LP) return LibUnripeConvert.beansToPeg(); // UrBEAN -> BEAN if (toToken == C.BEAN) return type(uint256).max; } revert("Convert: Tokens not supported"); } function getAmountOut(address fromToken, address toToken, uint256 fromAmount) internal view returns (uint256) { /// BEAN:3CRV LP -> BEAN if (fromToken == C.CURVE_BEAN_METAPOOL && toToken == C.BEAN) return LibCurveConvert.getBeanAmountOut(C.CURVE_BEAN_METAPOOL, fromAmount); /// BEAN -> BEAN:3CRV LP // NOTE: cannot convert due to bean:3crv dewhitelisting // if (fromToken == C.BEAN && toToken == C.CURVE_BEAN_METAPOOL) // return LibCurveConvert.getLPAmountOut(C.CURVE_BEAN_METAPOOL, fromAmount); /// urLP -> urBEAN if (fromToken == C.UNRIPE_LP && toToken == C.UNRIPE_BEAN) return LibUnripeConvert.getBeanAmountOut(fromAmount); /// urBEAN -> urLP if (fromToken == C.UNRIPE_BEAN && toToken == C.UNRIPE_LP) return LibUnripeConvert.getLPAmountOut(fromAmount); // Lambda -> Lambda & // Anti-Lambda -> Lambda if (fromToken == toToken) return fromAmount; // Bean -> Well LP Token if (fromToken == C.BEAN && toToken.isWell()) return LibWellConvert.getLPAmountOut(toToken, fromAmount); // Well LP Token -> Bean if (fromToken.isWell() && toToken == C.BEAN) return LibWellConvert.getBeanAmountOut(fromToken, fromAmount); // UrBEAN -> Bean if (fromToken == C.UNRIPE_BEAN && toToken == C.BEAN) return LibChopConvert.getConvertedUnderlyingOut(fromToken, fromAmount); // UrBEANETH -> BEANETH if (fromToken == C.UNRIPE_LP && toToken == LibBarnRaise.getBarnRaiseWell()) return LibChopConvert.getConvertedUnderlyingOut(fromToken, fromAmount); revert("Convert: Tokens not supported"); } }
// 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, UNRIPE_TO_RIPE, ANTI_LAMBDA_LAMBDA } /// @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) ); } /// @notice Decoder for the lambdaConvert function lambdaConvert(bytes memory self) internal pure returns (uint256 amount, address token) { (, amount, token) = abi.decode(self, (ConvertKind, uint256, address)); } /// @notice Decoder for the antiLambdaConvert /// @dev contains an additional address parameter for the account to update the deposit /// and a bool to indicate whether to decrease the bdv function antiLambdaConvert(bytes memory self) internal pure returns (uint256 amount, address token, address account, bool decreaseBDV) { (, amount, token, account) = abi.decode(self, (ConvertKind, uint256, address , address)); decreaseBDV = true; } }
// 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."); } }
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import {LibConvertData} from "./LibConvertData.sol"; /** * @title LibLambdaConvert * @author Publius, deadmanwalking */ library LibLambdaConvert { using LibConvertData for bytes; /** * @notice This function returns the full input for use in lambda convert * In lambda convert, the account converts from and to the same token. */ function convert(bytes memory convertData) internal pure returns ( address tokenOut, address tokenIn, uint256 amountOut, uint256 amountIn ) { (amountIn, tokenIn) = convertData.lambdaConvert(); tokenOut = tokenIn; amountOut = amountIn; } /** * @notice This function returns the full input for use in anti-lamda convert * In anti lamda convert, any user can convert on behalf of an account * to update a deposit's bdv. * This is why the additional 'account' parameter is returned. */ function antiConvert(bytes memory convertData) internal pure returns ( address tokenOut, address tokenIn, uint256 amountOut, uint256 amountIn, address account, bool decreaseBDV ) { (amountIn, tokenIn, account, decreaseBDV) = convertData.antiLambdaConvert(); tokenOut = tokenIn; amountOut = amountIn; } }
// 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) ); } }
// 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"; import {LibBarnRaise} from "contracts/libraries/LibBarnRaise.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, IBean(C.UNRIPE_BEAN).totalSupply()) .mul(LibUnripe.percentLPRecapped()) .div(LibUnripe.percentBeansRecapped()); ( uint256 outUnderlyingAmount, uint256 inUnderlyingAmount ) = LibWellConvert._wellRemoveLiquidityTowardsPeg( LibUnripe.unripeToUnderlying(tokenIn, lp, IBean(C.UNRIPE_LP).totalSupply()), minAmountOut, LibBarnRaise.getBarnRaiseWell() ); 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, IBean(C.UNRIPE_LP).totalSupply()) .mul(LibUnripe.percentBeansRecapped()) .div(LibUnripe.percentLPRecapped()); ( uint256 outUnderlyingAmount, uint256 inUnderlyingAmount ) = LibWellConvert._wellAddLiquidityTowardsPeg( LibUnripe.unripeToUnderlying(tokenIn, beans, IBean(C.UNRIPE_BEAN).totalSupply()), minAmountOut, LibBarnRaise.getBarnRaiseWell() ); 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( LibBarnRaise.getBarnRaiseWell() ); beans = LibUnripe.underlyingToUnripe( C.UNRIPE_BEAN, underlyingBeans ); } function lpToPeg() internal view returns (uint256 lp) { uint256 underlyingLP = LibWellConvert.lpToPeg( LibBarnRaise.getBarnRaiseWell() ); lp = LibUnripe.underlyingToUnripe(C.UNRIPE_LP, underlyingLP); } function getLPAmountOut(uint256 amountIn) internal view returns (uint256 lp) { uint256 beans = LibUnripe.unripeToUnderlying( C.UNRIPE_BEAN, amountIn, IBean(C.UNRIPE_BEAN).totalSupply() ); lp = LibWellConvert.getLPAmountOut(LibBarnRaise.getBarnRaiseWell(), 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, IBean(C.UNRIPE_LP).totalSupply() ); bean = LibWellConvert.getBeanAmountOut(LibBarnRaise.getBarnRaiseWell(), lp); bean = LibUnripe .underlyingToUnripe(C.UNRIPE_BEAN, bean) .mul(LibUnripe.percentBeansRecapped()) .div(LibUnripe.percentLPRecapped()); } }
/* 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(); require(LibWell.isWell(well), "Convert: Invalid Well"); 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(); require(LibWell.isWell(well), "Convert: Invalid Well"); 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, ) = _beansToPeg(well); require(maxBeans > 0, "Convert: P must be >= 1."); beansConverted = beans > maxBeans ? maxBeans : beans; C.bean().transfer(well, beansConverted); lp = IWell(well).sync( address(this), minLP ); } }
// 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); } }
// 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); } }
// 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() ); } }
/* 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; } }
// 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 } } }
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import {IWell} from "contracts/interfaces/basin/IWell.sol"; import {C} from "contracts/C.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {AppStorage, LibAppStorage} from "contracts/libraries/LibAppStorage.sol"; /** * @title LibBarnRaise * @author Brendan * @notice Library fetching Barn Raise Token */ library LibBarnRaise { function getBarnRaiseToken() internal view returns (address) { IERC20[] memory tokens = IWell(getBarnRaiseWell()).tokens(); return address(address(tokens[0]) == C.BEAN ? tokens[1] : tokens[0]); } function getBarnRaiseWell() internal view returns (address) { AppStorage storage s = LibAppStorage.diamondStorage(); return s.u[C.UNRIPE_LP].underlyingToken == address(0) ? C.BEAN_WSTETH_WELL : s.u[C.UNRIPE_LP].underlyingToken; } }
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import {LibUnripe, SafeMath, AppStorage} from "contracts/libraries/LibUnripe.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IBean} from "contracts/interfaces/IBean.sol"; import {LibAppStorage} from "./LibAppStorage.sol"; /** * @title LibChop * @author deadmanwalking */ library LibChop { using SafeMath for uint256; /** * @notice Chops an Unripe Token into its Ripe Token. * @dev The output amount is based on the % of Sprouts that are Rinsable or Rinsed * and the % of Fertilizer that has been bought. * @param unripeToken The address of the Unripe Token to be Chopped. * @param amount The amount of the of the Unripe Token to be Chopped. * @return underlyingToken The address of Ripe Tokens received after the Chop. * @return underlyingAmount The amount of Ripe Tokens received after the Chop. */ function chop( address unripeToken, uint256 amount, uint256 supply ) internal returns (address underlyingToken, uint256 underlyingAmount) { AppStorage storage s = LibAppStorage.diamondStorage(); underlyingAmount = LibUnripe.getPenalizedUnderlying(unripeToken, amount, supply); // remove the underlying amount and decrease s.recapitalized if token is unripe LP LibUnripe.removeUnderlying(unripeToken, underlyingAmount); underlyingToken = s.u[unripeToken].underlyingToken; } }
/* SPDX-License-Identifier: MIT */ pragma experimental ABIEncoderV2; pragma solidity =0.7.6; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ import {IDiamondCut} from "../interfaces/IDiamondCut.sol"; import {IDiamondLoupe} from "../interfaces/IDiamondLoupe.sol"; import {IERC165} from "../interfaces/IERC165.sol"; library LibDiamond { bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); struct FacetAddressAndPosition { address facetAddress; uint96 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array } struct FacetFunctionSelectors { bytes4[] functionSelectors; uint256 facetAddressPosition; // position of facetAddress in facetAddresses array } struct DiamondStorage { // maps function selector to the facet address and // the position of the selector in the facetFunctionSelectors.selectors array mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition; // maps facet addresses to function selectors mapping(address => FacetFunctionSelectors) facetFunctionSelectors; // facet addresses address[] facetAddresses; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; // owner of the contract address contractOwner; } function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function setContractOwner(address _newOwner) internal { DiamondStorage storage ds = diamondStorage(); address previousOwner = ds.contractOwner; ds.contractOwner = _newOwner; emit OwnershipTransferred(previousOwner, _newOwner); } function contractOwner() internal view returns (address contractOwner_) { contractOwner_ = diamondStorage().contractOwner; } function enforceIsOwnerOrContract() internal view { require(msg.sender == diamondStorage().contractOwner || msg.sender == address(this), "LibDiamond: Must be contract or owner" ); } function enforceIsContractOwner() internal view { require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner"); } event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); function addDiamondFunctions( address _diamondCutFacet, address _diamondLoupeFacet ) internal { IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](2); bytes4[] memory functionSelectors = new bytes4[](1); functionSelectors[0] = IDiamondCut.diamondCut.selector; cut[0] = IDiamondCut.FacetCut({facetAddress: _diamondCutFacet, action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors}); functionSelectors = new bytes4[](5); functionSelectors[0] = IDiamondLoupe.facets.selector; functionSelectors[1] = IDiamondLoupe.facetFunctionSelectors.selector; functionSelectors[2] = IDiamondLoupe.facetAddresses.selector; functionSelectors[3] = IDiamondLoupe.facetAddress.selector; functionSelectors[4] = IERC165.supportsInterface.selector; cut[1] = IDiamondCut.FacetCut({ facetAddress: _diamondLoupeFacet, action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors }); diamondCut(cut, address(0), ""); } // Internal function version of diamondCut function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action; if (action == IDiamondCut.FacetCutAction.Add) { addFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors); } else if (action == IDiamondCut.FacetCutAction.Replace) { replaceFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors); } else if (action == IDiamondCut.FacetCutAction.Remove) { removeFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors); } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal { require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); DiamondStorage storage ds = diamondStorage(); require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)"); uint96 selectorPosition = uint96(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length); // add new facet address if it does not exist if (selectorPosition == 0) { addFacet(ds, _facetAddress); } for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists"); addFunction(ds, selector, selectorPosition, _facetAddress); selectorPosition++; } } function replaceFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal { require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); DiamondStorage storage ds = diamondStorage(); require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)"); uint96 selectorPosition = uint96(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length); // add new facet address if it does not exist if (selectorPosition == 0) { addFacet(ds, _facetAddress); } for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; require(oldFacetAddress != _facetAddress, "LibDiamondCut: Can't replace function with same function"); removeFunction(ds, oldFacetAddress, selector); addFunction(ds, selector, selectorPosition, _facetAddress); selectorPosition++; } } function removeFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal { require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); DiamondStorage storage ds = diamondStorage(); // if function does not exist then do nothing and return require(_facetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)"); for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; removeFunction(ds, oldFacetAddress, selector); } } function addFacet(DiamondStorage storage ds, address _facetAddress) internal { enforceHasContractCode(_facetAddress, "LibDiamondCut: New facet has no code"); ds.facetFunctionSelectors[_facetAddress].facetAddressPosition = ds.facetAddresses.length; ds.facetAddresses.push(_facetAddress); } function addFunction(DiamondStorage storage ds, bytes4 _selector, uint96 _selectorPosition, address _facetAddress) internal { ds.selectorToFacetAndPosition[_selector].functionSelectorPosition = _selectorPosition; ds.facetFunctionSelectors[_facetAddress].functionSelectors.push(_selector); ds.selectorToFacetAndPosition[_selector].facetAddress = _facetAddress; } function removeFunction(DiamondStorage storage ds, address _facetAddress, bytes4 _selector) internal { require(_facetAddress != address(0), "LibDiamondCut: Can't remove function that doesn't exist"); // an immutable function is a function defined directly in a diamond require(_facetAddress != address(this), "LibDiamondCut: Can't remove immutable function"); // replace selector with last selector, then delete last selector uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition; uint256 lastSelectorPosition = ds.facetFunctionSelectors[_facetAddress].functionSelectors.length - 1; // if not the same then replace _selector with lastSelector if (selectorPosition != lastSelectorPosition) { bytes4 lastSelector = ds.facetFunctionSelectors[_facetAddress].functionSelectors[lastSelectorPosition]; ds.facetFunctionSelectors[_facetAddress].functionSelectors[selectorPosition] = lastSelector; ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint96(selectorPosition); } // delete the last selector ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop(); delete ds.selectorToFacetAndPosition[_selector]; // if no more selectors for facet address then delete the facet address if (lastSelectorPosition == 0) { // replace facet address with last facet address and delete last facet address uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1; uint256 facetAddressPosition = ds.facetFunctionSelectors[_facetAddress].facetAddressPosition; if (facetAddressPosition != lastFacetAddressPosition) { address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition]; ds.facetAddresses[facetAddressPosition] = lastFacetAddress; ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = facetAddressPosition; } ds.facetAddresses.pop(); delete ds.facetFunctionSelectors[_facetAddress].facetAddressPosition; } } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty"); } else { require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)"); if (_init != address(this)) { enforceHasContractCode(_init, "LibDiamondCut: _init address has no code"); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } } function enforceHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } }
/* SPDX-License-Identifier: MIT */ pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol"; import {AppStorage, LibAppStorage} from "./LibAppStorage.sol"; import {LibSafeMath128} from "./LibSafeMath128.sol"; import {C} from "../C.sol"; import {LibUnripe} from "./LibUnripe.sol"; import {IWell} from "contracts/interfaces/basin/IWell.sol"; import {LibBarnRaise} from "./LibBarnRaise.sol"; import {LibDiamond} from "contracts/libraries/LibDiamond.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {LibWell} from "contracts/libraries/Well/LibWell.sol"; import {LibUsdOracle} from "contracts/libraries/Oracle/LibUsdOracle.sol"; /** * @author Publius * @title Fertilizer **/ library LibFertilizer { using SafeMath for uint256; using LibSafeMath128 for uint128; using SafeCast for uint256; using SafeERC20 for IERC20; using LibWell for address; event SetFertilizer(uint128 id, uint128 bpf); // 6 - 3 uint128 private constant PADDING = 1e3; uint128 private constant DECIMALS = 1e6; uint128 private constant REPLANT_SEASON = 6074; uint128 private constant RESTART_HUMIDITY = 2500; uint128 private constant END_DECREASE_SEASON = REPLANT_SEASON + 461; /** * @dev Adds a new fertilizer to Beanstalk, updates global state, * the season queue, and returns the corresponding fertilizer id. * @param season The season the fertilizer is added. * @param fertilizerAmount The amount of Fertilizer to add. * @param minLP The minimum amount of LP to add. * @return id The id of the Fertilizer. */ function addFertilizer( uint128 season, uint256 tokenAmountIn, uint256 fertilizerAmount, uint256 minLP ) internal returns (uint128 id) { AppStorage storage s = LibAppStorage.diamondStorage(); uint128 fertilizerAmount128 = fertilizerAmount.toUint128(); // Calculate Beans Per Fertilizer and add to total owed uint128 bpf = getBpf(season); s.unfertilizedIndex = s.unfertilizedIndex.add( fertilizerAmount.mul(bpf) ); // Get id id = s.bpf.add(bpf); // Update Total and Season supply s.fertilizer[id] = s.fertilizer[id].add(fertilizerAmount128); s.activeFertilizer = s.activeFertilizer.add(fertilizerAmount); // Add underlying to Unripe Beans and Unripe LP addUnderlying(tokenAmountIn, fertilizerAmount.mul(DECIMALS), minLP); // If not first time adding Fertilizer with this id, return if (s.fertilizer[id] > fertilizerAmount128) return id; // If first time, log end Beans Per Fertilizer and add to Season queue. push(id); emit SetFertilizer(id, bpf); } /** * @dev Calculates the Beans Per Fertilizer for a given season. * Forluma is bpf = Humidity + 1000 * 1,000 * @param id The id of the Fertilizer. * @return bpf The Beans Per Fertilizer. */ function getBpf(uint128 id) internal pure returns (uint128 bpf) { bpf = getHumidity(id).add(1000).mul(PADDING); } /** * @dev Calculates the Humidity for a given season. * The Humidity was 500% prior to Replant, after which it dropped to 250% (Season 6074) * and then decreased by an additional 0.5% each Season until it reached 20%. * The Humidity will remain at 20% until all Available Fertilizer is purchased. * @param id The season. * @return humidity The corresponding Humidity. */ function getHumidity(uint128 id) internal pure returns (uint128 humidity) { if (id == 0) return 5000; if (id >= END_DECREASE_SEASON) return 200; uint128 humidityDecrease = id.sub(REPLANT_SEASON).mul(5); humidity = RESTART_HUMIDITY.sub(humidityDecrease); } /** * @dev Any token contributions should already be transferred to the Barn Raise Well to allow for a gas efficient liquidity * addition through the use of `sync`. See {FertilizerFacet.mintFertilizer} for an example. */ function addUnderlying(uint256 tokenAmountIn, uint256 usdAmount, uint256 minAmountOut) internal { AppStorage storage s = LibAppStorage.diamondStorage(); // Calculate how many new Deposited Beans will be minted uint256 percentToFill = usdAmount.mul(C.precision()).div( remainingRecapitalization() ); uint256 newDepositedBeans; if (C.unripeBean().totalSupply() > s.u[C.UNRIPE_BEAN].balanceOfUnderlying) { newDepositedBeans = (C.unripeBean().totalSupply()).sub( s.u[C.UNRIPE_BEAN].balanceOfUnderlying ); newDepositedBeans = newDepositedBeans.mul(percentToFill).div( C.precision() ); } // Calculate how many Beans to add as LP uint256 newDepositedLPBeans = usdAmount.mul(C.exploitAddLPRatio()).div( DECIMALS ); // Mint the Deposited Beans to Beanstalk. C.bean().mint( address(this), newDepositedBeans ); // Mint the LP Beans and add liquidity to the well. address barnRaiseWell = LibBarnRaise.getBarnRaiseWell(); address barnRaiseToken = LibBarnRaise.getBarnRaiseToken(); C.bean().mint( address(this), newDepositedLPBeans ); IERC20(barnRaiseToken).transferFrom( msg.sender, address(this), uint256(tokenAmountIn) ); IERC20(barnRaiseToken).approve(barnRaiseWell, uint256(tokenAmountIn)); C.bean().approve(barnRaiseWell, newDepositedLPBeans); uint256[] memory tokenAmountsIn = new uint256[](2); IERC20[] memory tokens = IWell(barnRaiseWell).tokens(); (tokenAmountsIn[0], tokenAmountsIn[1]) = tokens[0] == C.bean() ? (newDepositedLPBeans, tokenAmountIn) : (tokenAmountIn, newDepositedLPBeans); uint256 newLP = IWell(barnRaiseWell).addLiquidity( tokenAmountsIn, minAmountOut, address(this), type(uint256).max ); // Increment underlying balances of Unripe Tokens LibUnripe.incrementUnderlying(C.UNRIPE_BEAN, newDepositedBeans); LibUnripe.incrementUnderlying(C.UNRIPE_LP, newLP); s.recapitalized = s.recapitalized.add(usdAmount); } /** * @dev Adds a fertilizer id in the queue. * fFirst is the lowest active Fertilizer Id (see AppStorage) * (start of linked list that is stored by nextFid). * The highest active Fertilizer Id * (end of linked list that is stored by nextFid). * @param id The id of the fertilizer. */ function push(uint128 id) internal { AppStorage storage s = LibAppStorage.diamondStorage(); if (s.fFirst == 0) { // Queue is empty s.season.fertilizing = true; s.fLast = id; s.fFirst = id; } else if (id <= s.fFirst) { // Add to front of queue setNext(id, s.fFirst); s.fFirst = id; } else if (id >= s.fLast) { // Add to back of queue setNext(s.fLast, id); s.fLast = id; } else { // Add to middle of queue uint128 prev = s.fFirst; uint128 next = getNext(prev); // Search for proper place in line while (id > next) { prev = next; next = getNext(next); } setNext(prev, id); setNext(id, next); } } /** * @dev Returns the dollar amount remaining for beanstalk to recapitalize. * @return remaining The dollar amount remaining. */ function remainingRecapitalization() internal view returns (uint256 remaining) { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 totalDollars = getTotalRecapDollarsNeeded(); if (s.recapitalized >= totalDollars) return 0; return totalDollars.sub(s.recapitalized); } /** * @dev Returns the total dollar amount needed to recapitalize Beanstalk. * @return totalDollars The total dollar amount. */ function getTotalRecapDollarsNeeded() internal view returns(uint256) { return getTotalRecapDollarsNeeded(C.unripeLP().totalSupply()); } /** * @dev Returns the total dollar amount needed to recapitalize Beanstalk * for the supply of Unripe LP. * @param urLPsupply The supply of Unripe LP. * @return totalDollars The total dollar amount. */ function getTotalRecapDollarsNeeded(uint256 urLPsupply) internal pure returns(uint256) { uint256 totalDollars = C .dollarPerUnripeLP() .mul(urLPsupply) .div(DECIMALS); totalDollars = totalDollars / 1e6 * 1e6; // round down to nearest USDC return totalDollars; } /** * @dev Removes the first fertilizer id in the queue. * fFirst is the lowest active Fertilizer Id (see AppStorage) * (start of linked list that is stored by nextFid). * @return bool Whether the queue is empty. */ function pop() internal returns (bool) { AppStorage storage s = LibAppStorage.diamondStorage(); uint128 first = s.fFirst; s.activeFertilizer = s.activeFertilizer.sub(getAmount(first)); uint128 next = getNext(first); if (next == 0) { // If all Unfertilized Beans have been fertilized, delete line. require(s.activeFertilizer == 0, "Still active fertilizer"); s.fFirst = 0; s.fLast = 0; s.season.fertilizing = false; return false; } s.fFirst = getNext(first); return true; } /** * @dev Returns the amount (supply) of fertilizer for a given id. * @param id The id of the fertilizer. */ function getAmount(uint128 id) internal view returns (uint256) { AppStorage storage s = LibAppStorage.diamondStorage(); return s.fertilizer[id]; } /** * @dev Returns the next fertilizer id in the list given a fertilizer id. * nextFid is a linked list of Fertilizer Ids ordered by Id number. (See AppStorage) * @param id The id of the fertilizer. */ function getNext(uint128 id) internal view returns (uint128) { AppStorage storage s = LibAppStorage.diamondStorage(); return s.nextFid[id]; } /** * @dev Sets the next fertilizer id in the list given a fertilizer id. * nextFid is a linked list of Fertilizer Ids ordered by Id number. (See AppStorage) * @param id The id of the fertilizer. * @param next The id of the next fertilizer. */ function setNext(uint128 id, uint128 next) internal { AppStorage storage s = LibAppStorage.diamondStorage(); s.nextFid[id] = next; } function beginBarnRaiseMigration(address well) internal { AppStorage storage s = LibAppStorage.diamondStorage(); require(well.isWell(), "Fertilizer: Not a Whitelisted Well."); // The Barn Raise only supports 2 token Wells where 1 token is Bean and the // other is supported by the Lib Usd Oracle. IERC20[] memory tokens = IWell(well).tokens(); require(tokens.length == 2, "Fertilizer: Well must have 2 tokens."); require( tokens[0] == C.bean() || tokens[1] == C.bean(), "Fertilizer: Well must have BEAN." ); // Check that Lib Usd Oracle supports the non-Bean token in the Well. LibUsdOracle.getTokenPrice(address(tokens[tokens[0] == C.bean() ? 1 : 0])); uint256 balanceOfUnderlying = s.u[C.UNRIPE_LP].balanceOfUnderlying; IERC20(s.u[C.UNRIPE_LP].underlyingToken).safeTransfer( LibDiamond.diamondStorage().contractOwner, balanceOfUnderlying ); LibUnripe.decrementUnderlying(C.UNRIPE_LP, balanceOfUnderlying); LibUnripe.switchUnderlyingToken(C.UNRIPE_LP, well); } }
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {AppStorage, LibAppStorage} from "./LibAppStorage.sol"; /** * @title LibLockedUnderlying * @author Brendan * @notice Library to calculate the number of Underlying Tokens that would be locked if all of * the Unripe Tokens are Chopped. */ library LibLockedUnderlying { using SafeMath for uint256; uint256 constant DECIMALS = 1e6; /** * @notice Return the amount of Underlying Tokens that would be locked if all of the Unripe Tokens * were chopped. */ function getLockedUnderlying( address unripeToken, uint256 recapPercentPaid ) external view returns (uint256 lockedUnderlying) { AppStorage storage s = LibAppStorage.diamondStorage(); return s .u[unripeToken] .balanceOfUnderlying .mul(getPercentLockedUnderlying(unripeToken, recapPercentPaid)) .div(1e18); } /** * @notice Return the % of Underlying Tokens that would be locked if all of the Unripe Tokens * were chopped. * @param unripeToken The address of the Unripe Token * @param recapPercentPaid The % of the Unripe Token that has been recapitalized * * @dev Solves the below equation for N_{⌈U/i⌉}: * N_{t+1} = N_t - π * i / (U - i * t) * where: * - N_t is the number of Underlying Tokens at step t * - U is the starting number of Unripe Tokens * - π is the amount recapitalized * - i is the number of Unripe Beans that are chopped at each step. i ~= 46,659 is used as this is aboutr * the average Unripe Beans held per Farmer with a non-zero balance. * * The equation is solved by using a lookup table of N_{⌈U/i⌉} values for different values of * U and R (The solution is independent of N) as solving iteratively is too computationally * expensive and there is no more efficient way to solve the equation. * * The lookup threshold assumes no decimal precision. This library only supports * unripe tokens with 6 decimals. */ function getPercentLockedUnderlying( address unripeToken, uint256 recapPercentPaid ) private view returns (uint256 percentLockedUnderlying) { uint256 unripeSupply = IERC20(unripeToken).totalSupply().div(DECIMALS); if (unripeSupply < 1_000_000) return 0; // If < 1_000_000 Assume all supply is unlocked. if (unripeSupply > 90_000_000) { if (recapPercentPaid > 0.1e6) { if (recapPercentPaid > 0.21e6) { if (recapPercentPaid > 0.38e6) { if (recapPercentPaid > 0.45e6) { return 0.2691477202198985e18; // 90,000,000, 0.9 } else { return 0.4245158057296602e18; // 90,000,000, 0.45 } } else if (recapPercentPaid > 0.29e6) { if (recapPercentPaid > 0.33e6) { return 0.46634353868138156e18; // 90,000,000, 0.38 } else { return 0.5016338055689489e18; // 90,000,000, 0.33 } } else if (recapPercentPaid > 0.25e6) { if (recapPercentPaid > 0.27e6) { return 0.5339474169852891e18; // 90,000,000, 0.29 } else { return 0.5517125463928281e18; // 90,000,000, 0.27 } } else { if (recapPercentPaid > 0.23e6) { return 0.5706967827806866e18; // 90,000,000, 0.25 } else { return 0.5910297971598633e18; // 90,000,000, 0.23 } } } else { if (recapPercentPaid > 0.17e6) { if (recapPercentPaid > 0.19e6) { return 0.6128602937515535e18; // 90,000,000, 0.21 } else { return 0.6363596297698088e18; // 90,000,000, 0.19 } } else if (recapPercentPaid > 0.14e6) { if (recapPercentPaid > 0.15e6) { return 0.6617262928282552e18; // 90,000,000, 0.17 } else { return 0.6891914824733962e18; // 90,000,000, 0.15 } } else if (recapPercentPaid > 0.12e6) { if (recapPercentPaid > 0.13e6) { return 0.7037939098015373e18; // 90,000,000, 0.14 } else { return 0.719026126689054e18; // 90,000,000, 0.13 } } else { if (recapPercentPaid > 0.11e6) { return 0.7349296649399273e18; // 90,000,000, 0.12 } else { return 0.7515497824365694e18; // 90,000,000, 0.11 } } } } else { if (recapPercentPaid > 0.08e6) { if (recapPercentPaid > 0.09e6) { return 0.7689358898389307e18; // 90,000,000, 0.1 } else { return 0.7871420372030031e18; // 90,000,000, 0.09 } } else if (recapPercentPaid > 0.06e6) { if (recapPercentPaid > 0.07e6) { return 0.8062274705566613e18; // 90,000,000, 0.08 } else { return 0.8262572704372576e18; // 90,000,000, 0.07 } } else if (recapPercentPaid > 0.05e6) { if (recapPercentPaid > 0.055e6) { return 0.8473030868055568e18; // 90,000,000, 0.06 } else { return 0.8582313943058512e18; // 90,000,000, 0.055 } } else if (recapPercentPaid > 0.04e6) { if (recapPercentPaid > 0.045e6) { return 0.8694439877186144e18; // 90,000,000, 0.05 } else { return 0.8809520709014887e18; // 90,000,000, 0.045 } } if (recapPercentPaid > 0.03e6) { if (recapPercentPaid > 0.035e6) { return 0.892767442816813e18; // 90,000,000, 0.04 } else { return 0.9049025374937268e18; // 90,000,000, 0.035 } } else if (recapPercentPaid > 0.02e6) { if (recapPercentPaid > 0.025e6) { return 0.9173704672485867e18; // 90,000,000, 0.03 } else { return 0.9301850694774185e18; // 90,000,000, 0.025 } } else if (recapPercentPaid > 0.01e6) { if (recapPercentPaid > 0.015e6) { return 0.9433609573691148e18; // 90,000,000, 0.02 } else { return 0.9569135749274008e18; // 90,000,000, 0.015 } } else { if (recapPercentPaid > 0.005e6) { return 0.9708592567341514e18; // 90,000,000, 0.01 } else { return 0.9852152929368606e18; // 90,000,000, 0.005 } } } } else if (unripeSupply > 10_000_000) { if (recapPercentPaid > 0.1e6) { if (recapPercentPaid > 0.21e6) { if (recapPercentPaid > 0.38e6) { if (recapPercentPaid > 0.45e6) { return 0.2601562129458128e18; // 10,000,000, 0.9 } else { return 0.41636482361397587e18; // 10,000,000, 0.45 } } else if (recapPercentPaid > 0.29e6) { if (recapPercentPaid > 0.33e6) { return 0.4587658967980477e18; // 10,000,000, 0.38 } else { return 0.49461012289361284e18; // 10,000,000, 0.33 } } else if (recapPercentPaid > 0.25e6) { if (recapPercentPaid > 0.27e6) { return 0.5274727741119862e18; // 10,000,000, 0.29 } else { return 0.5455524222086705e18; // 10,000,000, 0.27 } } else { if (recapPercentPaid > 0.23e6) { return 0.5648800673771895e18; // 10,000,000, 0.25 } else { return 0.5855868704094357e18; // 10,000,000, 0.23 } } } else { if (recapPercentPaid > 0.17e6) { if (recapPercentPaid > 0.19e6) { return 0.6078227259058706e18; // 10,000,000, 0.21 } else { return 0.631759681239449e18; // 10,000,000, 0.19 } } else if (recapPercentPaid > 0.14e6) { if (recapPercentPaid > 0.15e6) { return 0.6575961226208655e18; // 10,000,000, 0.17 } else { return 0.68556193437231e18; // 10,000,000, 0.15 } } else if (recapPercentPaid > 0.12e6) { if (recapPercentPaid > 0.13e6) { return 0.7004253506676488e18; // 10,000,000, 0.14 } else { return 0.7159249025906607e18; // 10,000,000, 0.13 } } else { if (recapPercentPaid > 0.11e6) { return 0.7321012978270447e18; // 10,000,000, 0.12 } else { return 0.7489987232590216e18; // 10,000,000, 0.11 } } } } else { if (recapPercentPaid > 0.08e6) { if (recapPercentPaid > 0.09e6) { return 0.766665218442354e18; // 10,000,000, 0.1 } else { return 0.7851530975272665e18; // 10,000,000, 0.09 } } else if (recapPercentPaid > 0.06e6) { if (recapPercentPaid > 0.07e6) { return 0.8045194270172396e18; // 10,000,000, 0.08 } else { return 0.8248265680621683e18; // 10,000,000, 0.07 } } else if (recapPercentPaid > 0.05e6) { if (recapPercentPaid > 0.055e6) { return 0.8461427935458878e18; // 10,000,000, 0.06 } else { return 0.8572024359670631e18; // 10,000,000, 0.055 } } else if (recapPercentPaid > 0.04e6) { if (recapPercentPaid > 0.045e6) { return 0.8685429921113414e18; // 10,000,000, 0.05 } else { return 0.8801749888510111e18; // 10,000,000, 0.045 } } if (recapPercentPaid > 0.03e6) { if (recapPercentPaid > 0.035e6) { return 0.8921094735432339e18; // 10,000,000, 0.04 } else { return 0.9043580459814082e18; // 10,000,000, 0.035 } } else if (recapPercentPaid > 0.02e6) { if (recapPercentPaid > 0.025e6) { return 0.9169328926903124e18; // 10,000,000, 0.03 } else { return 0.9298468237651341e18; // 10,000,000, 0.025 } } else if (recapPercentPaid > 0.01e6) { if (recapPercentPaid > 0.015e6) { return 0.9431133124739901e18; // 10,000,000, 0.02 } else if (recapPercentPaid > 0.01e6) { return 0.956746537865208e18; // 10,000,000, 0.015 } else if (recapPercentPaid > 0.005e6) { return 0.970761430644659e18; // 10,000,000, 0.01 } else { return 0.9851737226151924e18; // 10,000,000, 0.005 } } } } else if (unripeSupply > 1_000_000) { if (recapPercentPaid > 0.1e6) { if (recapPercentPaid > 0.21e6) { if (recapPercentPaid > 0.38e6) { if (recapPercentPaid > 0.45e6) { return 0.22204456672314377e18; // 1,000,000, 0.9 } else { return 0.4085047499499631e18; // 1,000,000, 0.45 } } else if (recapPercentPaid > 0.29e6) { if (recapPercentPaid > 0.33e6) { return 0.46027376814120946e18; // 1,000,000, 0.38 } else { return 0.5034753937446597e18; // 1,000,000, 0.33 } } else if (recapPercentPaid > 0.25e6) { if (recapPercentPaid > 0.27e6) { return 0.5424140302842413e18; // 1,000,000, 0.29 } else { return 0.5635119158156667e18; // 1,000,000, 0.27 } } else { if (recapPercentPaid > 0.23e6) { return 0.5857864256253713e18; // 1,000,000, 0.25 } else { return 0.6093112868361505e18; // 1,000,000, 0.23 } } } else { if (recapPercentPaid > 0.17e6) { if (recapPercentPaid > 0.19e6) { return 0.6341650041820726e18; // 1,000,000, 0.21 } else { return 0.6604311671564058e18; // 1,000,000, 0.19 } } else if (recapPercentPaid > 0.14e6) { if (recapPercentPaid > 0.15e6) { return 0.6881987762208012e18; // 1,000,000, 0.17 } else { return 0.7175625891924777e18; // 1,000,000, 0.15 } } else if (recapPercentPaid > 0.12e6) { if (recapPercentPaid > 0.13e6) { return 0.7328743482797107e18; // 1,000,000, 0.14 } else { return 0.7486234889866461e18; // 1,000,000, 0.13 } } else { if (recapPercentPaid > 0.11e6) { return 0.7648236427602255e18; // 1,000,000, 0.12 } else { return 0.7814888739548376e18; // 1,000,000, 0.11 } } } } else { if (recapPercentPaid > 0.08e6) { if (recapPercentPaid > 0.09e6) { return 0.798633693358723e18; // 1,000,000, 0.1 } else { return 0.8162730721263407e18; // 1,000,000, 0.09 } } else if (recapPercentPaid > 0.06e6) { if (recapPercentPaid > 0.07e6) { return 0.8344224561281671e18; // 1,000,000, 0.08 } else { return 0.8530977807297004e18; // 1,000,000, 0.07 } } else if (recapPercentPaid > 0.05e6) { if (recapPercentPaid > 0.055e6) { return 0.8723154860117406e18; // 1,000,000, 0.06 } else { return 0.8821330107890434e18; // 1,000,000, 0.055 } } else if (recapPercentPaid > 0.04e6) { if (recapPercentPaid > 0.045e6) { return 0.8920925324443344e18; // 1,000,000, 0.05 } else { return 0.9021962549951718e18; // 1,000,000, 0.045 } } if (recapPercentPaid > 0.03e6) { if (recapPercentPaid > 0.035e6) { return 0.9124464170270961e18; // 1,000,000, 0.04 } else { return 0.9228452922244391e18; // 1,000,000, 0.035 } } else if (recapPercentPaid > 0.02e6) { if (recapPercentPaid > 0.025e6) { return 0.9333951899089395e18; // 1,000,000, 0.03 } else { return 0.9440984555862713e18; // 1,000,000, 0.025 } } else if (recapPercentPaid > 0.01e6) { if (recapPercentPaid > 0.015e6) { return 0.9549574715005937e18; // 1,000,000, 0.02 } else if (recapPercentPaid > 0.01e6) { return 0.9659746571972349e18; // 1,000,000, 0.015 } else if (recapPercentPaid > 0.005e6) { return 0.9771524700936202e18; // 1,000,000, 0.01 } else { return 0.988493406058558e18; // 1,000,000, 0.005 } } } } } }
// 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; } }
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; 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"; import {LibWell} from "./Well/LibWell.sol"; import {Call, IWell} from "contracts/interfaces/basin/IWell.sol"; import {IWellFunction} from "contracts/interfaces/basin/IWellFunction.sol"; import {LibLockedUnderlying} from "./LibLockedUnderlying.sol"; import {LibFertilizer} from "./LibFertilizer.sol"; /** * @title LibUnripe * @author Publius * @notice Library for handling functionality related to Unripe Tokens and their Ripe Tokens. */ 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; /** * @notice Returns the percentage that Unripe Beans have been recapitalized. */ 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()); } /** * @notice Returns the percentage that Unripe LP have been recapitalized. */ function percentLPRecapped() internal view returns (uint256 percent) { AppStorage storage s = LibAppStorage.diamondStorage(); return C.unripeLPPerDollar().mul(s.recapitalized).div(C.unripeLP().totalSupply()); } /** * @notice Increments the underlying balance of an Unripe Token. * @param token The address of the unripe token. * @param amount The amount of the of the unripe token to be added to the storage reserves */ 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)); } /** * @notice Decrements the underlying balance of an Unripe Token. * @param token The address of the Unripe Token. * @param amount The amount of the of the Unripe Token to be removed from storage reserves */ 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)); } /** * @notice Calculates the amount of Ripe Tokens that underly a given amount of Unripe Tokens. * @param unripeToken The address of the Unripe Token * @param unripe The amount of Unripe Tokens. * @return underlying The amount of Ripe Tokens that underly the Unripe Tokens. */ function unripeToUnderlying( address unripeToken, uint256 unripe, uint256 supply ) internal view returns (uint256 underlying) { AppStorage storage s = LibAppStorage.diamondStorage(); underlying = s.u[unripeToken].balanceOfUnderlying.mul(unripe).div(supply); } /** * @notice Calculates the amount of Unripe Tokens that are underlaid by a given amount of Ripe Tokens. * @param unripeToken The address of the Unripe Tokens. * @param underlying The amount of Ripe Tokens. * @return unripe The amount of the of the Unripe Tokens that are underlaid by the Ripe Tokens. */ 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 ); } /** * @notice Adds Ripe Tokens to an Unripe Token. Also, increments the recapitalized * amount proportionally if the Unripe Token is Unripe LP. * @param token The address of the Unripe Token to add Ripe Tokens to. * @param underlying The amount of the of the underlying token to be taken as input. */ 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); } /** * @notice Removes Ripe Tokens from an Unripe Token. Also, decrements the recapitalized * amount proportionally if the Unripe Token is Unripe LP. * @param token The address of the unripe token to be removed. * @param underlying The amount of the of the underlying token to be removed. */ 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); } /** * @notice Calculates the the penalized amount of Ripe Tokens corresponding to * the amount of Unripe Tokens that are Chopped according to the current Chop Rate. * The new chop rate is %Recapitalized^2. */ function getPenalizedUnderlying( address unripeToken, uint256 amount, uint256 supply ) internal view returns (uint256 redeem) { require(isUnripe(unripeToken), "not vesting"); AppStorage storage s = LibAppStorage.diamondStorage(); // getTotalRecapDollarsNeeded() queries for the total urLP supply which is burned upon a chop // If the token being chopped is unripeLP, getting the current supply here is inaccurate due to the burn // Instead, we use the supply passed in as an argument to getTotalRecapDollarsNeeded since the supply variable // here is the total urToken supply queried before burnning the unripe token uint256 totalUsdNeeded = unripeToken == C.UNRIPE_LP ? LibFertilizer.getTotalRecapDollarsNeeded(supply) : LibFertilizer.getTotalRecapDollarsNeeded(); // chop rate = total redeemable * (%DollarRecapitalized)^2 * share of unripe tokens // redeem = totalRipeUnderlying * (usdValueRaised/totalUsdNeeded)^2 * UnripeAmountIn/UnripeSupply; // But totalRipeUnderlying = CurrentUnderlying * totalUsdNeeded/usdValueRaised to get the total underlying // redeem = currentRipeUnderlying * (usdValueRaised/totalUsdNeeded) * UnripeAmountIn/UnripeSupply uint256 underlyingAmount = s.u[unripeToken].balanceOfUnderlying; if(totalUsdNeeded == 0) { // when totalUsdNeeded == 0, the barnraise has been fully recapitalized. redeem = underlyingAmount.mul(amount).div(supply); } else { redeem = underlyingAmount.mul(s.recapitalized).div(totalUsdNeeded).mul(amount).div(supply); } // cap `redeem to `balanceOfUnderlying in the case that `s.recapitalized` exceeds `totalUsdNeeded`. // this can occur due to unripe LP chops. if(redeem > underlyingAmount) redeem = underlyingAmount; } /** * @notice returns the total percentage that beanstalk has recapitalized. * @dev this is calculated by the ratio of s.recapitalized and the total dollars the barnraise needs to raise. * returns the same precision as `getRecapPaidPercentAmount` (100% recapitalized = 1e6). */ function getTotalRecapitalizedPercent() internal view returns (uint256 recapitalizedPercent) { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 totalUsdNeeded = LibFertilizer.getTotalRecapDollarsNeeded(); if (totalUsdNeeded == 0) { return 1e6; // if zero usd needed, full recap has happened } return s.recapitalized.mul(DECIMALS).div(totalUsdNeeded); } /** * @notice Returns the amount of beans that are locked in the unripe token. * @dev Locked beans are the beans that are forfeited if the unripe token is chopped. * @param reserves the reserves of the LP that underly the unripe token. * @dev reserves are used as a parameter for gas effiency purposes (see LibEvaluate.calcLPToSupplyRatio}. */ function getLockedBeans( uint256[] memory reserves ) internal view returns (uint256 lockedAmount) { lockedAmount = LibLockedUnderlying .getLockedUnderlying(C.UNRIPE_BEAN, getTotalRecapitalizedPercent()) .add(getLockedBeansFromLP(reserves)); } /** * @notice Returns the amount of beans that are locked in the unripeLP token. * @param reserves the reserves of the LP that underly the unripe token. */ function getLockedBeansFromLP( uint256[] memory reserves ) internal view returns (uint256 lockedBeanAmount) { AppStorage storage s = LibAppStorage.diamondStorage(); // if reserves return 0, then skip calculations. if (reserves[0] == 0) return 0; uint256 lockedLpAmount = LibLockedUnderlying.getLockedUnderlying( C.UNRIPE_LP, getTotalRecapitalizedPercent() ); address underlying = s.u[C.UNRIPE_LP].underlyingToken; uint256 beanIndex = LibWell.getBeanIndexFromWell(underlying); // lpTokenSupply is calculated rather than calling totalSupply(), // because the Well's lpTokenSupply is not MEV resistant. Call memory wellFunction = IWell(underlying).wellFunction(); uint lpTokenSupply = IWellFunction(wellFunction.target).calcLpTokenSupply( reserves, wellFunction.data ); lockedBeanAmount = lockedLpAmount.mul(reserves[beanIndex]).div(lpTokenSupply); } /** * @notice Calculates the penalized amount based the amount of Sprouts that are Rinsable * or Rinsed (Fertilized). * @param amount The amount of the Unripe Tokens. * @return penalizedAmount The penalized amount of the Ripe Tokens received from Chopping. */ function getRecapPaidPercentAmount( uint256 amount ) internal view returns (uint256 penalizedAmount) { AppStorage storage s = LibAppStorage.diamondStorage(); return s.fertilizedIndex.mul(amount).div(s.unfertilizedIndex); } /** * @notice Returns true if the token is unripe. */ function isUnripe(address unripeToken) internal view returns (bool unripe) { AppStorage storage s = LibAppStorage.diamondStorage(); unripe = s.u[unripeToken].underlyingToken != address(0); } function getTotalRecapDollarsNeeded() internal view returns (uint256 totalUsdNeeded) { return LibFertilizer.getTotalRecapDollarsNeeded(); } }
/** * 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; uint256 constant PRECISION = 1e6; // use 6 decimal precision. // timeout for Oracles with a 1 hour heartbeat. uint256 constant FOUR_HOUR_TIMEOUT = 14400; // timeout for Oracles with a 1 day heartbeat. uint256 constant FOUR_DAY_TIMEOUT = 345600; struct TwapVariables { uint256 cumulativePrice; uint256 endTimestamp; uint256 lastTimestamp; } /** * @dev Returns the price of a given `priceAggregator` * Return value has 6 decimal precision. * Returns 0 if Chainlink's price feed is broken or frozen. **/ function getPrice( address priceAggregatorAddress, uint256 maxTimeout ) internal view returns (uint256 price) { IChainlinkAggregator priceAggregator = IChainlinkAggregator(priceAggregatorAddress); // 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; if (checkForInvalidTimestampOrAnswer(timestamp, answer, block.timestamp, maxTimeout)) { return 0; } // Adjust to 6 decimal precision. return uint256(answer).mul(PRECISION).div(10 ** decimals); } catch { // If call to Chainlink aggregator reverts, return a price of 0 indicating failure return 0; } } /** * @dev Returns the TWAP price from the Chainlink Oracle over the past `lookback` seconds. * Return value has 6 decimal precision. * Returns 0 if Chainlink's price feed is broken or frozen. **/ function getTwap( address priceAggregatorAddress, uint256 maxTimeout, uint256 lookback ) internal view returns (uint256 price) { IChainlinkAggregator priceAggregator = IChainlinkAggregator(priceAggregatorAddress); // 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; if (checkForInvalidTimestampOrAnswer(timestamp, answer, block.timestamp, maxTimeout)) { return 0; } TwapVariables memory t; t.endTimestamp = block.timestamp.sub(lookback); // Check if last round was more than `lookback` ago. if (timestamp <= t.endTimestamp) { return uint256(answer).mul(PRECISION).div(10 ** decimals); } else { t.lastTimestamp = block.timestamp; // Loop through previous rounds and compute cumulative sum until // a round at least `lookback` seconds ago is reached. while (timestamp > t.endTimestamp) { t.cumulativePrice = t.cumulativePrice.add( uint256(answer).mul(t.lastTimestamp.sub(timestamp)) ); roundId -= 1; t.lastTimestamp = timestamp; (answer, timestamp) = getRoundData(priceAggregator, roundId); if (checkForInvalidTimestampOrAnswer( timestamp, answer, t.lastTimestamp, maxTimeout )) { return 0; } } t.cumulativePrice = t.cumulativePrice.add( uint256(answer).mul(t.lastTimestamp.sub(t.endTimestamp)) ); return t.cumulativePrice.mul(PRECISION).div(10 ** decimals).div(lookback); } } catch { // If call to Chainlink aggregator reverts, return a price of 0 indicating failure return 0; } } function getRoundData( IChainlinkAggregator priceAggregator, uint80 roundId ) private view returns (int256, uint256) { try priceAggregator.getRoundData(roundId) returns ( uint80 /* roundId */, int256 _answer, uint256 /* startedAt */, uint256 _timestamp, uint80 /* answeredInRound */ ) { return (_answer, _timestamp); } catch { return (-1, 0); } } function checkForInvalidTimestampOrAnswer( uint256 timestamp, int256 answer, uint256 currentTimestamp, uint256 maxTimeout ) private pure returns (bool) { // Check for an invalid timeStamp that is 0, or in the future if (timestamp == 0 || timestamp > currentTimestamp) return true; // Check if Chainlink's price feed has timed out if (currentTimestamp.sub(timestamp) > maxTimeout) return true; // Check for non-positive price if (answer <= 0) return true; } }
/** * SPDX-License-Identifier: MIT **/ pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import {LibChainlinkOracle} from "./LibChainlinkOracle.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {LibAppStorage, AppStorage} from "contracts/libraries/LibAppStorage.sol"; import {C} from "contracts/C.sol"; import {LibOracleHelpers} from "contracts/libraries/Oracle/LibOracleHelpers.sol"; /** * @title Eth Usd Oracle Library * @notice Contains functionalty to fetch a manipulation resistant ETH/USD price. * @dev * The Oracle uses the ETH/USD Chainlink Oracle to fetch the price. * The oracle will fail (return 0) if the Chainlink Oracle is broken or frozen (See: {LibChainlinkOracle}). **/ library LibEthUsdOracle { using SafeMath for uint256; /////////////////// ORACLES /////////////////// address constant ETH_USD_CHAINLINK_PRICE_AGGREGATOR = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419; /////////////////////////////////////////////// function getEthUsdPriceFromStorageIfSaved() internal view returns (uint256) { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 priceInStorage = s.usdTokenPrice[C.BEAN_ETH_WELL]; if (priceInStorage == 1) { return getEthUsdPrice(); } return priceInStorage; } /** * @dev Returns the instantaneous ETH/USD price * Return value has 6 decimal precision. * Returns 0 if the ETH/USD Chainlink Oracle is broken or frozen. **/ function getEthUsdPrice() internal view returns (uint256) { return LibChainlinkOracle.getPrice(ETH_USD_CHAINLINK_PRICE_AGGREGATOR, LibChainlinkOracle.FOUR_HOUR_TIMEOUT); } /** * @dev Returns the ETH/USD price with the option of using a TWA lookback. * Use `lookback = 0` for the instantaneous price. `lookback > 0` for a TWAP. * Return value has 6 decimal precision. * Returns 0 if the ETH/USD Chainlink Oracle is broken or frozen. **/ function getEthUsdPrice(uint256 lookback) internal view returns (uint256) { return lookback > 0 ? LibChainlinkOracle.getTwap( ETH_USD_CHAINLINK_PRICE_AGGREGATOR, LibChainlinkOracle.FOUR_HOUR_TIMEOUT, lookback ) : LibChainlinkOracle.getPrice( ETH_USD_CHAINLINK_PRICE_AGGREGATOR, LibChainlinkOracle.FOUR_HOUR_TIMEOUT ); } }
/** * SPDX-License-Identifier: MIT **/ pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title Oracle Helpers Library * @author brendan * @notice Contains functionalty common to multiple Oracle libraries. **/ library LibOracleHelpers { using SafeMath for uint256; uint256 constant ONE = 1e18; /** * 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%. * Always use the bigger price as the denominator, thereby making sure that in whichever of the two cases explained in audit report (M-03), * i.e if x > y or not a fixed percentDifference is provided and this can then be accurately checked against protocol's set MAX_DIFFERENCE value. */ function getPercentDifference( uint x, uint y ) internal pure returns (uint256 percentDifference) { if (x == y) { percentDifference = 0; } else if (x < y) { percentDifference = x.mul(ONE).div(y); percentDifference = ONE - percentDifference; } else { percentDifference = y.mul(ONE).div(x); percentDifference = ONE - percentDifference; } return percentDifference; } }
/** * 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 { // All instantaneous queries of Uniswap Oracles should use a 15 minute lookback. uint32 constant internal FIFTEEN_MINUTES = 900; /** * @dev Uses `pool`'s Uniswap V3 Oracle to get the TWAP price of `token1` in `token2` over the * last `lookback` seconds. * Return value has 6 decimal precision. * Returns 0 if {IUniswapV3Pool.observe} reverts. */ function getTwap(uint32 lookback, address pool, address token1, address token2, uint128 oneToken) internal view returns (uint256 price) { (bool success, int24 tick) = consult(pool, lookback); if (!success) return 0; price = OracleLibrary.getQuoteAtTick(tick, oneToken, token1, token2); } /** * @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 {} } }
/** * SPDX-License-Identifier: MIT **/ pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import {LibEthUsdOracle} from "./LibEthUsdOracle.sol"; import {LibWstethUsdOracle} from "./LibWstethUsdOracle.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; function getUsdPrice(address token) internal view returns (uint256) { return getUsdPrice(token, 0); } /** * @dev Returns the price of a given token in in USD with the option of using a lookback. (Usd:token Price) * `lookback` should be 0 if the instantaneous price is desired. Otherwise, it should be the * TWAP lookback in seconds. * If using a non-zero lookback, it is recommended to use a substantially large `lookback` * (> 900 seconds) to protect against manipulation. */ function getUsdPrice(address token, uint256 lookback) internal view returns (uint256) { if (token == C.WETH) { uint256 ethUsdPrice = LibEthUsdOracle.getEthUsdPrice(lookback); if (ethUsdPrice == 0) return 0; return uint256(1e24).div(ethUsdPrice); } if (token == C.WSTETH) { uint256 wstethUsdPrice = LibWstethUsdOracle.getWstethUsdPrice(lookback); if (wstethUsdPrice == 0) return 0; return uint256(1e24).div(wstethUsdPrice); } revert("Oracle: Token not supported."); } function getTokenPrice(address token) internal view returns (uint256) { return getTokenPrice(token, 0); } /** * @notice returns the price of a given token in USD (token:Usd Price) * @dev if ETH returns 1000 USD, this function returns 1000 * (ignoring decimal precision) */ function getTokenPrice(address token, uint256 lookback) internal view returns (uint256) { if (token == C.WETH) { uint256 ethUsdPrice = LibEthUsdOracle.getEthUsdPrice(lookback); if (ethUsdPrice == 0) return 0; return ethUsdPrice; } if (token == C.WSTETH) { uint256 wstethUsdPrice = LibWstethUsdOracle.getWstethUsdPrice(lookback); if (wstethUsdPrice == 0) return 0; return wstethUsdPrice; } revert("Oracle: Token not supported."); } }
/** * 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"; import {LibAppStorage, AppStorage} from "contracts/libraries/LibAppStorage.sol"; import {C} from "contracts/C.sol"; import {LibOracleHelpers} from "contracts/libraries/Oracle/LibOracleHelpers.sol"; interface IWsteth { function stEthPerToken() external view returns (uint256); } /** * @title Wsteth Eth Oracle Library * @author brendan * @notice Computes the wstETH:ETH price. * @dev * The oracle reads from 4 data sources: * a. wstETH:stETH Redemption Rate: (0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0) * b. stETH:ETH Chainlink Oracle: (0x86392dC19c0b719886221c78AB11eb8Cf5c52812) * c. wstETH:ETH Uniswap Pool: (0x109830a1AAaD605BbF02a9dFA7B0B92EC2FB7dAa) * d. stETH:ETH Redemption: (1:1) * * It then computes the wstETH:ETH price in 3 ways: * 1. wstETH -> ETH via Chainlink: a * b * 2. wstETH -> ETH via wstETH:ETH Uniswap Pool: c * 1 * 3. wstETH -> ETH via stETH redemption: a * d * * It then computes a wstETH:ETH price by taking the minimum of (3) and either the average of (1) and (2) * if (1) and (2) are within `MAX_DIFFERENCE` from each other or (1). **/ library LibWstethEthOracle { using SafeMath for uint256; // The maximum percent difference such that the oracle assumes no manipulation is occuring. uint256 constant MAX_DIFFERENCE = 0.01e18; // 1% uint256 constant CHAINLINK_DENOMINATOR = 1e6; uint128 constant ONE = 1e18; uint128 constant AVERAGE_DENOMINATOR = 2; uint128 constant PRECISION_DENOMINATOR = 1e12; /////////////////// ORACLES /////////////////// address constant WSTETH_ETH_CHAINLINK_PRICE_AGGREGATOR = 0x86392dC19c0b719886221c78AB11eb8Cf5c52812; address internal constant WSTETH_ETH_UNIV3_01_POOL = 0x109830a1AAaD605BbF02a9dFA7B0B92EC2FB7dAa; // 0.01% pool /////////////////////////////////////////////// /** * @dev Returns the instantaneous wstETH/ETH price * Return value has 6 decimal precision. * Returns 0 if the either the Chainlink Oracle or Uniswap Oracle cannot fetch a valid price. **/ function getWstethEthPrice() internal view returns (uint256) { return getWstethEthPrice(0); } /** * @dev Returns the wstETH/ETH price with the option of using a TWA lookback. * Return value has 6 decimal precision. * Returns 0 if the either the Chainlink Oracle or Uniswap Oracle cannot fetch a valid price. **/ function getWstethEthPrice(uint256 lookback) internal view returns (uint256 wstethEthPrice) { uint256 chainlinkPrice = lookback == 0 ? LibChainlinkOracle.getPrice(WSTETH_ETH_CHAINLINK_PRICE_AGGREGATOR, LibChainlinkOracle.FOUR_DAY_TIMEOUT) : LibChainlinkOracle.getTwap(WSTETH_ETH_CHAINLINK_PRICE_AGGREGATOR, LibChainlinkOracle.FOUR_DAY_TIMEOUT, lookback); // Check if the chainlink price is broken or frozen. if (chainlinkPrice == 0) return 0; uint256 stethPerWsteth = IWsteth(C.WSTETH).stEthPerToken(); chainlinkPrice = chainlinkPrice.mul(stethPerWsteth).div(CHAINLINK_DENOMINATOR); // Uniswap V3 only supports a uint32 lookback. if (lookback > type(uint32).max) return 0; uint256 uniswapPrice = LibUniswapOracle.getTwap( lookback == 0 ? LibUniswapOracle.FIFTEEN_MINUTES : uint32(lookback), WSTETH_ETH_UNIV3_01_POOL, C.WSTETH, C.WETH, ONE ); // Check if the uniswapPrice oracle fails. if (uniswapPrice == 0) return 0; if (LibOracleHelpers.getPercentDifference(chainlinkPrice, uniswapPrice) < MAX_DIFFERENCE) { wstethEthPrice = chainlinkPrice.add(uniswapPrice).div(AVERAGE_DENOMINATOR); if (wstethEthPrice > stethPerWsteth) wstethEthPrice = stethPerWsteth; wstethEthPrice = wstethEthPrice.div(PRECISION_DENOMINATOR); } } }
/** * SPDX-License-Identifier: MIT **/ pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import {IWsteth, LibWstethEthOracle, SafeMath} from "contracts/libraries/Oracle/LibWstethEthOracle.sol"; import {LibEthUsdOracle} from "contracts/libraries/Oracle/LibEthUsdOracle.sol"; /** * @title Wsteth USD Oracle Library * @author brendan * @notice Computes the wStETH:USD price. * @dev * The oracle reads from 2 data sources: * a. LibWstethEthOracle * b. LibEthUsdOracle * * The wStEth:USD price is computed as: a * b **/ library LibWstethUsdOracle { using SafeMath for uint256; uint256 constant ORACLE_PRECISION = 1e6; /** * @dev Returns the instantaneous wstETH/USD price * Return value has 6 decimal precision. * Returns 0 if the either LibWstethEthOracle or LibEthUsdOracle cannot fetch a valid price. **/ function getWstethUsdPrice() internal view returns (uint256) { return getWstethUsdPrice(0); } /** * @dev Returns the wstETH/USD price with the option of using a TWA lookback. * Return value has 6 decimal precision. * Returns 0 if the either LibWstethEthOracle or LibEthUsdOracle cannot fetch a valid price. **/ function getWstethUsdPrice(uint256 lookback) internal view returns (uint256) { return LibWstethEthOracle.getWstethEthPrice(lookback).mul( LibEthUsdOracle.getEthUsdPrice(lookback) ).div(ORACLE_PRECISION); } }
/* SPDX-License-Identifier: MIT */ pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {ICumulativePump} from "contracts/interfaces/basin/pumps/ICumulativePump.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IWell, Call} from "contracts/interfaces/basin/IWell.sol"; import {C} from "contracts/C.sol"; import {AppStorage, LibAppStorage, Storage} from "../LibAppStorage.sol"; import {LibUsdOracle} from "contracts/libraries/Oracle/LibUsdOracle.sol"; import {LibSafeMath128} from "contracts/libraries/LibSafeMath128.sol"; /** * @title Well Library * Contains helper functions for common Well related functionality. **/ library LibWell { using SafeMath for uint256; using LibSafeMath128 for uint128; // The BDV Selector that all Wells should be whitelisted with. bytes4 internal constant WELL_BDV_SELECTOR = 0xc84c7727; function getRatiosAndBeanIndex(IERC20[] memory tokens) internal view returns ( uint[] memory ratios, uint beanIndex, bool success ) { return getRatiosAndBeanIndex(tokens, 0); } /** * @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, uint256 lookback) 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]), lookback); 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 the non-Bean token within a Well. * Assumes a well with 2 tokens only, with Bean being one of them. * Cannot fail (and thus revert), as wells cannot have 2 of the same tokens as the pairing. */ function getNonBeanTokenAndIndexFromWell( address well ) internal view returns (address, uint256) { IERC20[] memory tokens = IWell(well).tokens(); for (uint256 i; i < tokens.length; i++) { if (address(tokens[i]) != C.BEAN) { return (address(tokens[i]), i); } } } /** * @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 == WELL_BDV_SELECTOR; } /** * @notice gets the non-bean usd liquidity of a well, * using the twa reserves and price in storage. * * @dev this is done for gas efficency purposes, rather than calling the pump multiple times. * This function should be called after the reserves for the well have been set. * Currently this is only done in {seasonFacet.sunrise}. * * if LibWell.getUsdTokenPriceForWell() returns 1, then this function is called without the reserves being set. * if s.usdTokenPrice[well] or s.twaReserves[well] returns 0, then the oracle failed to compute * a valid price this Season, and thus beanstalk cannot calculate the usd liquidity. */ function getWellTwaUsdLiquidityFromReserves( address well, uint256[] memory twaReserves ) internal view returns (uint256 usdLiquidity) { uint256 tokenUsd = getUsdTokenPriceForWell(well); (address token, uint256 j) = getNonBeanTokenAndIndexFromWell(well); if (tokenUsd > 1) { return twaReserves[j].mul(1e18).div(tokenUsd); } // if tokenUsd == 0, then the beanstalk could not compute a valid eth price, // and should return 0. if s.twaReserves[C.BEAN_ETH_WELL].reserve1 is 0, the previous if block will return 0. if (tokenUsd == 0) { return 0; } // if the function reaches here, then this is called outside the sunrise function // (i.e, seasonGetterFacet.getLiquidityToSupplyRatio()).We use LibUsdOracle // to get the price. This should never be reached during sunrise and thus // should not impact gas. return LibUsdOracle.getTokenPrice(token).mul(twaReserves[j]).div(1e6); } /** * @dev Sets the price in {AppStorage.usdTokenPrice} given a set of ratios. * It assumes that the ratios correspond to the Constant Product Well indexes. */ function setUsdTokenPriceForWell(address well, uint256[] memory ratios) internal { AppStorage storage s = LibAppStorage.diamondStorage(); // If the reserves length is 0, then {LibWellMinting} failed to compute // valid manipulation resistant reserves and thus the price is set to 0 // indicating that the oracle failed to compute a valid price this Season. if (ratios.length == 0) { s.usdTokenPrice[well] = 0; } else { (, uint256 j) = getNonBeanTokenAndIndexFromWell(well); s.usdTokenPrice[well] = ratios[j]; } } /** * @notice Returns the USD / TKN price stored in {AppStorage.usdTokenPrice}. * @dev assumes TKN has 18 decimals. */ function getUsdTokenPriceForWell(address well) internal view returns (uint tokenUsd) { tokenUsd = LibAppStorage.diamondStorage().usdTokenPrice[well]; } /** * @notice resets token price for a well to 1. * @dev must be called at the end of sunrise() once the * price is not needed anymore to save gas. */ function resetUsdTokenPriceForWell(address well) internal { LibAppStorage.diamondStorage().usdTokenPrice[well] = 1; } /** * @dev Sets the twaReserves in {AppStorage.usdTokenPrice}. * assumes the twaReserve indexes correspond to the Constant Product Well indexes. * if the length of the twaReserves is 0, then the minting oracle is off. * */ function setTwaReservesForWell(address well, uint256[] memory twaReserves) internal { AppStorage storage s = LibAppStorage.diamondStorage(); // if the length of twaReserves is 0, then return 0. // the length of twaReserves should never be 1, but // is added to prevent revert. if (twaReserves.length <= 1) { delete s.twaReserves[well].reserve0; delete s.twaReserves[well].reserve1; } else { // safeCast not needed as the reserves are uint128 in the wells. s.twaReserves[well].reserve0 = uint128(twaReserves[0]); s.twaReserves[well].reserve1 = uint128(twaReserves[1]); } } /** * @notice Returns the TKN / USD price stored in {AppStorage.usdTokenPrice}. * @dev assumes TKN has 18 decimals. */ function getTwaReservesForWell( address well ) internal view returns (uint256[] memory twaReserves) { AppStorage storage s = LibAppStorage.diamondStorage(); twaReserves = new uint256[](2); twaReserves[0] = s.twaReserves[well].reserve0; twaReserves[1] = s.twaReserves[well].reserve1; } /** * @notice resets token price for a well to 1. * @dev must be called at the end of sunrise() once the * price is not needed anymore to save gas. */ function resetTwaReservesForWell(address well) internal { AppStorage storage s = LibAppStorage.diamondStorage(); s.twaReserves[well].reserve0 = 1; s.twaReserves[well].reserve1 = 1; } /** * @notice returns the price in terms of TKN/BEAN. * (if eth is 1000 beans, this function will return 1000e6); */ function getBeanTokenPriceFromTwaReserves(address well) internal view returns (uint256 price) { AppStorage storage s = LibAppStorage.diamondStorage(); // s.twaReserve[well] should be set prior to this function being called. if (s.twaReserves[well].reserve0 == 0 || s.twaReserves[well].reserve1 == 0) { price = 0; } else { // fetch the bean index from the well in order to properly return the bean price. if (getBeanIndexFromWell(well) == 0) { price = uint256(s.twaReserves[well].reserve0).mul(1e18).div(s.twaReserves[well].reserve1); } else { price = uint256(s.twaReserves[well].reserve1).mul(1e18).div(s.twaReserves[well].reserve0); } } } function getTwaReservesFromStorageOrBeanstalkPump( address well ) internal view returns (uint256[] memory twaReserves) { twaReserves = getTwaReservesForWell(well); if (twaReserves[0] == 1) { twaReserves = getTwaReservesFromBeanstalkPump(well); } } /** * @notice gets the TwaReserves of a given well. * @dev only supports wells that are whitelisted in beanstalk. * the initial timestamp and reserves is the timestamp of the start * of the last season. wrapped in try/catch to return gracefully. */ function getTwaReservesFromBeanstalkPump( address well ) internal view returns (uint256[] memory) { AppStorage storage s = LibAppStorage.diamondStorage(); return getTwaReservesFromPump( well, s.wellOracleSnapshots[well], uint40(s.season.timestamp) ); } /** * @notice returns the twa reserves for well, * given the cumulative reserves and timestamp. * @dev wrapped in a try/catch to return gracefully. */ function getTwaReservesFromPump( address well, bytes memory cumulativeReserves, uint40 timestamp ) internal view returns (uint256[] memory) { Call[] memory pump = IWell(well).pumps(); try ICumulativePump(pump[0].target).readTwaReserves( well, cumulativeReserves, timestamp, pump[0].data ) returns (uint[] memory twaReserves, bytes memory) { return twaReserves; } catch { return (new uint256[](2)); } } /** * @notice gets the TwaLiquidity of a given well. * @dev only supports wells that are whitelisted in beanstalk. * the initial timestamp and reserves is the timestamp of the start * of the last season. */ function getTwaLiquidityFromBeanstalkPump( address well, uint256 tokenUsdPrice ) internal view returns (uint256 usdLiquidity) { AppStorage storage s = LibAppStorage.diamondStorage(); (, uint256 j) = getNonBeanTokenAndIndexFromWell(well); Call[] memory pumps = IWell(well).pumps(); try ICumulativePump(pumps[0].target).readTwaReserves( well, s.wellOracleSnapshots[well], uint40(s.season.timestamp), pumps[0].data ) returns (uint[] memory twaReserves, bytes memory) { usdLiquidity = tokenUsdPrice.mul(twaReserves[j]).div(1e6); } catch { // if pump fails to return a value, return 0. usdLiquidity = 0; } } }
{ "optimizer": { "enabled": true, "runs": 100 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"}],"name":"getAmountOut","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"}],"name":"getMaxAmountIn","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"stateMutability":"view","type":"function"}]
Contract Creation Code
608060405234801561001057600080fd5b50613735806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c806324dd285c1461003b5780634aa0665214610064575b600080fd5b61004e610049366004612ecf565b610077565b60405161005b91906135b1565b60405180910390f35b61004e610072366004612f07565b61008c565b600061008383836100a3565b90505b92915050565b60006100998484846102b5565b90505b9392505050565b60006001600160a01b03831673c9c32cd16bf7efb85ff14e0c8603cc90f6f2ee491480156100e757506001600160a01b03821660008051602061367f833981519152145b156101105761010973c9c32cd16bf7efb85ff14e0c8603cc90f6f2ee496104f5565b9050610086565b816001600160a01b0316836001600160a01b031614156101335750600019610086565b6001600160a01b03831660008051602061367f8339815191521480156101665750610166826001600160a01b03166105a0565b1561017457610109826105e5565b610186836001600160a01b03166105a0565b80156101a857506001600160a01b03821660008051602061367f833981519152145b156101b657610109836105f7565b6001600160a01b0383166000805160206136e08339815191521415610226576001600160a01b0382166000805160206136c083398151915214156101fc57610109610986565b6102046109b9565b6001600160a01b0316826001600160a01b031614156102265750600019610086565b6001600160a01b0383166000805160206136c08339815191521415610294576001600160a01b0382166000805160206136e0833981519152141561026c57610109610a3c565b6001600160a01b03821660008051602061367f83398151915214156102945750600019610086565b60405162461bcd60e51b81526004016102ac9061351d565b60405180910390fd5b60006001600160a01b03841673c9c32cd16bf7efb85ff14e0c8603cc90f6f2ee491480156102f957506001600160a01b03831660008051602061367f833981519152145b156103235761031c73c9c32cd16bf7efb85ff14e0c8603cc90f6f2ee4983610a69565b905061009c565b6001600160a01b0384166000805160206136e083398151915214801561035f57506001600160a01b0383166000805160206136c0833981519152145b1561036d5761031c82610aea565b6001600160a01b0384166000805160206136c08339815191521480156103a957506001600160a01b0383166000805160206136e0833981519152145b156103b75761031c82610bd3565b826001600160a01b0316846001600160a01b031614156103d857508061009c565b6001600160a01b03841660008051602061367f83398151915214801561040b575061040b836001600160a01b03166105a0565b1561041a5761031c8383610c73565b61042c846001600160a01b03166105a0565b801561044e57506001600160a01b03831660008051602061367f833981519152145b1561045d5761031c8483610dd8565b6001600160a01b0384166000805160206136c083398151915214801561049957506001600160a01b03831660008051602061367f833981519152145b156104a85761031c8483610e17565b6001600160a01b0384166000805160206136e08339815191521480156104e657506104d16109b9565b6001600160a01b0316836001600160a01b0316145b156102945761031c8483610e17565b600080826001600160a01b03166314f059796040518163ffffffff1660e01b8152600401604080518083038186803b15801561053057600080fd5b505afa158015610544573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061056891906130a6565b905060006105768483610e94565b8251909150811061058c5760009250505061059b565b6105968282610edc565b925050505b919050565b6000806105ab610faf565b6001600160a01b03841660009081526039909101602052604090205460e01b6001600160e01b03191663c84c772760e01b14915050919050565b60006105f082610fb4565b5092915050565b600080826001600160a01b0316639d63848a6040518163ffffffff1660e01b815260040160006040518083038186803b15801561063357600080fd5b505afa158015610647573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261066f9190810190612f47565b90506000836001600160a01b0316630902f1ac6040518163ffffffff1660e01b815260040160006040518083038186803b1580156106ac57600080fd5b505afa1580156106c0573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526106e89190810190613123565b90506000846001600160a01b03166310dd08306040518163ffffffff1660e01b815260040160006040518083038186803b15801561072557600080fd5b505afa158015610739573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261076191908101906131a6565b905060008060006107718661122c565b925092509250806107945760405162461bcd60e51b81526004016102ac906134c1565b835160208501516040516316a1119f60e21b81526000926001600160a01b031691635a84467c916107cd918a9188918a9160040161339f565b60206040518083038186803b1580156107e557600080fd5b505afa1580156107f9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061081d9190613279565b90508086848151811061082c57fe5b60200260200101511161084957600097505050505050505061059b565b845160208601516040516253057f60e61b81526000926001600160a01b0316916314c15fc09161087d918b9160040161337a565b60206040518083038186803b15801561089557600080fd5b505afa1580156108a9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108cd9190613279565b9050818785815181106108dc57fe5b60200260200101818152505061097886600001516001600160a01b03166314c15fc08989602001516040518363ffffffff1660e01b815260040161092192919061337a565b60206040518083038186803b15801561093957600080fd5b505afa15801561094d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109719190613279565b8290611249565b9a9950505050505050505050565b6000806109996109946109b9565b6105f7565b90506109b36000805160206136e0833981519152826112a6565b91505090565b6000806109c4610faf565b6000805160206136e0833981519152600090815260408083016020529020549091506001600160a01b031615610a21576000805160206136e0833981519152600090815260408083016020529020546001600160a01b03166109b3565b73bea0000113b0d182f4064c86b71c315389e4715d91505090565b600080610a4f610a4a6109b9565b6105e5565b90506109b36000805160206136c0833981519152826112a6565b60405163cc2b27d760e01b81526000906001600160a01b0384169063cc2b27d790610a9a90859085906004016135d1565b60206040518083038186803b158015610ab257600080fd5b505afa158015610ac6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100839190613279565b600080610b846000805160206136e0833981519152846000805160206136e08339815191526001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b158015610b4757600080fd5b505afa158015610b5b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b7f9190613279565b61135e565b9050610b97610b916109b9565b82610dd8565b915061009c610ba4611399565b610bcd610baf611431565b610bc76000805160206136c0833981519152876112a6565b906114e4565b9061153d565b600080610c306000805160206136c0833981519152846000805160206136c08339815191526001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b158015610b4757600080fd5b9050610c43610c3d6109b9565b82610c73565b915061009c610c50611431565b610bcd610c5b611399565b610bc76000805160206136e0833981519152876112a6565b600080836001600160a01b0316639d63848a6040518163ffffffff1660e01b815260040160006040518083038186803b158015610caf57600080fd5b505afa158015610cc3573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610ceb9190810190612f47565b9050600081516001600160401b0381118015610d0657600080fd5b50604051908082528060200260200182016040528015610d30578160200160208202803683370190505b5090508381610d3e846115a4565b81518110610d4857fe5b6020908102919091010152604051638974eb0f60e01b81526001600160a01b03861690638974eb0f90610d7f908490600401613367565b60206040518083038186803b158015610d9757600080fd5b505afa158015610dab573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dcf9190613279565b95945050505050565b6040516308cfce0f60e41b81526000906001600160a01b03841690638cfce0f090610a9a90859060008051602061367f833981519152906004016135ba565b60006100838383856001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b158015610e5757600080fd5b505afa158015610e6b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e8f9190613279565b611610565b60006001600160a01b03831673c9c32cd16bf7efb85ff14e0c8603cc90f6f2ee491415610ec457610109826116ef565b60405162461bcd60e51b81526004016102ac90613428565b600080610ee761178c565b6001600160a01b03166376a2f0f06040518163ffffffff1660e01b815260040160206040518083038186803b158015610f1f57600080fd5b505afa158015610f33573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f579190613279565b90506000610f64856117a4565b90506000610f7282846117bb565b90506000610f888688835b602002015190611249565b9050610f96818884876118c7565b9050610fa481888487611a30565b979650505050505050565b600090565b6000806000836001600160a01b0316639d63848a6040518163ffffffff1660e01b815260040160006040518083038186803b158015610ff257600080fd5b505afa158015611006573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261102e9190810190612f47565b90506000846001600160a01b0316630902f1ac6040518163ffffffff1660e01b815260040160006040518083038186803b15801561106b57600080fd5b505afa15801561107f573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526110a79190810190613123565b90506000856001600160a01b03166310dd08306040518163ffffffff1660e01b815260040160006040518083038186803b1580156110e457600080fd5b505afa1580156110f8573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261112091908101906131a6565b90506060600061112f8561122c565b9097509092509050806111545760405162461bcd60e51b81526004016102ac906134c1565b825160208401516040516316a1119f60e21b81526000926001600160a01b031691635a84467c9161118d9189918c91899160040161339f565b60206040518083038186803b1580156111a557600080fd5b505afa1580156111b9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111dd9190613279565b90508487815181106111eb57fe5b602002602001015181116112085760009750505050505050611227565b84878151811061121457fe5b6020026020010151810397505050505050505b915091565b606060008061123c846000611afa565b9250925092509193909250565b6000828211156112a0576040805162461bcd60e51b815260206004820152601e60248201527f536166654d6174683a207375627472616374696f6e206f766572666c6f770000604482015290519081900360640190fd5b50900390565b6000806112b1610faf565b9050611356816040016000866001600160a01b03166001600160a01b0316815260200190815260200160002060010154610bcd85876001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561131e57600080fd5b505afa158015611332573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bc79190613279565b949350505050565b600080611369610faf565b6001600160a01b03861660009081526040808301602052902060010154909150610dcf908490610bcd90876114e4565b6000806113a4610faf565b90506109b36113b1611c3f565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156113e957600080fd5b505afa1580156113fd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114219190613279565b610bcd8360480154610bc7611c51565b60008061143c610faf565b90506109b3611449611c58565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561148157600080fd5b505afa158015611495573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114b99190613279565b6000805160206136c083398151915260009081526040808501602052902060010154610bcd90620f42405b6000826114f357506000610086565b8282028284828161150057fe5b04146100835760405162461bcd60e51b815260040180806020018281038252602181526020018061369f6021913960400191505060405180910390fd5b6000808211611593576040805162461bcd60e51b815260206004820152601a60248201527f536166654d6174683a206469766973696f6e206279207a65726f000000000000604482015290519081900360640190fd5b81838161159c57fe5b049392505050565b60005b81518110156115f8578181815181106115bc57fe5b60200260200101516001600160a01b031660008051602061367f8339815191526001600160a01b031614156115f05761059b565b6001016115a7565b60405162461bcd60e51b81526004016102ac90613554565b600061161b84611c6a565b6116375760405162461bcd60e51b81526004016102ac906134f8565b6000611641610faf565b905060006001600160a01b0386166000805160206136e0833981519152146116705761166b611c9a565b611679565b61167984611d21565b6001600160a01b03871660009081526040808501602052902060010154909150816116b3576116ac85610bcd83896114e4565b93506116d9565b6116d685610bcd88610bc786610bcd8960480154886114e490919063ffffffff16565b93505b808411156116e5578093505b5050509392505050565b60006100866c0c9f2c9cd04674edea40000000610bcd61170d611d47565b6001600160a01b031663bb7b8b806040518163ffffffff1660e01b815260040160206040518083038186803b15801561174557600080fd5b505afa158015611759573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061177d9190613279565b8560015b6020020151906114e4565b73c9c32cd16bf7efb85ff14e0c8603cc90f6f2ee4990565b6117ac612e04565b6100868264e8d4a51000611d5f565b6000806000805b60028110156117e9578581600281106117d757fe5b602002015192909201916001016117c2565b50816117fa57600092505050610086565b90915081906002840260005b6101008110156118ae578460005b600281101561184657600289826002811061182b57fe5b6020020151028783028161183b57fe5b049150600101611814565b50859350600381026064606319850186020401866002830260648689020401028161186d57fe5b04955083861180156118825750600184870311155b15611891575050505050610086565b6001868503116118a5575050505050610086565b50600101611806565b5060405162461bcd60e51b81526004016102ac9061357f565b6000806118d3856117a4565b905060006118ea6118e5888884610f7d565b611de9565b9050600061191c60405180604001604052808481526020018560016002811061190f57fe5b60200201519052866117bb565b9050611926612e04565b60006119418461193b8a610bcd878a87611781565b90611249565b90506119696402540be400611959621e8480846114e4565b8161196057fe5b04866000610f7d565b825261198661197e89610bcd86896001611781565b866001610f7d565b90506119ae6402540be40061199e621e8480846114e4565b816119a557fe5b04866001610f7d565b602083015260006119c188828587611dfa565b905060006119d0828583610f7d565b90506119e56119e0826001611249565b611ee3565b905060006119f76119e0888a84610f7d565b9050611a1f611a186402540be400610bcd64012a05f200610bc78688611249565b8290611ef4565b9d9c50505050505050505050505050565b6000611a3d858583610f7d565b84526000611a4a856117a4565b90506000611a5882856117bb565b90506000611a668683611249565b9050611aee86610bcd611a7761178c565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b158015611aaf57600080fd5b505afa158015611ac3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ae79190613279565b84906114e4565b98975050505050505050565b60606000806001905084516001600160401b0381118015611b1a57600080fd5b50604051908082528060200260200182016040528015611b44578160200160208202803683370190505b509250600019915060005b8551811015611c1557858181518110611b6457fe5b60200260200101516001600160a01b031660008051602061367f8339815191526001600160a01b03161415611bb757809250620f4240848281518110611ba657fe5b602002602001018181525050611c0d565b611bd4868281518110611bc657fe5b602002602001015186611f4e565b848281518110611be057fe5b602002602001018181525050838181518110611bf857fe5b602002602001015160001415611c0d57600091505b600101611b4f565b50600019821415611c385760405162461bcd60e51b81526004016102ac90613554565b9250925092565b6000805160206136e083398151915290565b621cc1b090565b6000805160206136c083398151915290565b600080611c75610faf565b6001600160a01b03938416600090815260409182016020522054909216151592915050565b6000611d1c611ca7611c3f565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b158015611cdf57600080fd5b505afa158015611cf3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d179190613279565b611d21565b905090565b600080611d37620f4240610bcd85610bc7611ff5565b620f424090819004029392505050565b73bebc44782c7db0a1a60cb6fe97d0b483032ff1c790565b611d67612e04565b6100838383611d74611d47565b6001600160a01b031663bb7b8b806040518163ffffffff1660e01b815260040160206040518083038186803b158015611dac57600080fd5b505afa158015611dc0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611de49190613279565b611ffc565b60006100868264e8d4a510006114e4565b60008080808460028902825b6002811015611e5157898114611e2e57888160028110611e2257fe5b60200201519450611e33565b611e49565b948401946002850283890281611e4557fe5b0492505b600101611e06565b506002810260648884020281611e6357fe5b0491506000816064890281611e7457fe5b048601905087965060005b60ff8110156118ae57879450888289600202010384898a020181611e9f57fe5b0497508488118015611eb45750600185890311155b15611ec55750505050505050611356565b600188860311611edb5750505050505050611356565b600101611e7f565b60006100868264e8d4a5100061153d565b600082820183811015610083576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b60006001600160a01b03831673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc21415611fad576000611f8083612036565b905080611f91576000915050610086565b611fa569d3c21bcecceda10000008261153d565b915050610086565b6001600160a01b038316737f39c581f595b53c5cb19bd0b3f8da6c935e2ca01415611fdd576000611f8083612085565b60405162461bcd60e51b81526004016102ac9061348a565b620818ba90565b612004612e04565b61201083856000611781565b815261202a670de0b6b3a7640000610bcd84876001611781565b60208201529392505050565b60008082116120645761205f735f4ec3df9cbd43714fe2740f5e3616155c5b84196138406120a3565b610086565b610086735f4ec3df9cbd43714fe2740f5e3616155c5b841961384084612201565b6000610086620f4240610bcd61209a85612036565b610bc78661244c565b6000808390506000816001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156120e457600080fd5b505afa925050508015612114575060408051601f3d908101601f19168201909252612111918101906132e0565b60015b61212357600092505050610086565b9050816001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a06040518083038186803b15801561215e57600080fd5b505afa92505050801561218e575060408051601f3d908101601f1916820190925261218b91810190613291565b60015b61219d57600092505050610086565b6001600160501b0385166121bb576000975050505050505050610086565b6121c78285428c612625565b156121dc576000975050505050505050610086565b6121f360ff8716600a0a610bcd86620f42406114e4565b975050505050505050610086565b6000808490506000816001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b15801561224257600080fd5b505afa925050508015612272575060408051601f3d908101601f1916820190925261226f918101906132e0565b60015b6122815760009250505061009c565b9050816001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a06040518083038186803b1580156122bc57600080fd5b505afa9250505080156122ec575060408051601f3d908101601f191682019092526122e991810190613291565b60015b6122fb5760009250505061009c565b6001600160501b03851661231957600097505050505050505061009c565b6123258285428d612625565b1561233a57600097505050505050505061009c565b612342612e22565b61234c428b611249565b60208201819052831161237f5761237060ff8816600a0a610bcd87620f42406114e4565b9850505050505050505061009c565b4260408201525b806020015183111561240b576123be6123b66123af85846040015161124990919063ffffffff16565b87906114e4565b825190611ef4565b815260408101839052600019909501946123d88887612669565b80945081965050506123f0838683604001518e612625565b156124065760009850505050505050505061009c565b612386565b61242c6123b66123af8360200151846040015161124990919063ffffffff16565b808252612370908b90610bcd9060ff8b16600a0a908290620f42406114e4565b600080821561247c576124777386392dc19c0b719886221c78ab11eb8cf5c528126205460085612201565b61249d565b61249d7386392dc19c0b719886221c78ab11eb8cf5c52812620546006120a3565b9050806124ae57600091505061059b565b6000737f39c581f595b53c5cb19bd0b3f8da6c935e2ca06001600160a01b031663035faf826040518163ffffffff1660e01b815260040160206040518083038186803b1580156124fd57600080fd5b505afa158015612511573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125359190613279565b9050612548620f4240610bcd84846114e4565b915063ffffffff8411156125615760009250505061059b565b60006125c385156125725785612576565b6103845b73109830a1aaad605bbf02a9dfa7b0b92ec2fb7daa737f39c581f595b53c5cb19bd0b3f8da6c935e2ca073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2670de0b6b3a7640000612707565b9050806125d6576000935050505061059b565b662386f26fc100006125e88483612736565b101561261d576125fd6002610bcd8584611ef4565b93508184111561260b578193505b61261a8464e8d4a5100061153d565b93505b505050919050565b600084158061263357508285115b1561264057506001611356565b8161264b8487611249565b111561265957506001611356565b6000841361135657506001611356565b600080836001600160a01b0316639a6fc8f5846040518263ffffffff1660e01b815260040161269891906135e2565b60a06040518083038186803b1580156126b057600080fd5b505afa9250505080156126e0575060408051601f3d908101601f191682019092526126dd91810190613291565b60015b6126f1575060001990506000612700565b50919450909250612700915050565b9250929050565b6000806000612716878961279e565b915091508161272a57600092505050610dcf565b611aee8185888861293b565b60008183141561274857506000610086565b818310156127775761276682610bcd85670de0b6b3a76400006114e4565b670de0b6b3a7640000039050610086565b61278d83610bcd84670de0b6b3a76400006114e4565b670de0b6b3a7640000039392505050565b60008063ffffffff83166127c45760405162461bcd60e51b81526004016102ac9061346e565b60408051600280825260608201835260009260208301908036833701905050905083816000815181106127f357fe5b602002602001019063ffffffff16908163ffffffff168152505060008160018151811061281c57fe5b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526001600160a01b0386169063883bdbfd9061285d9084906004016133de565b60006040518083038186803b15801561287557600080fd5b505afa9250505080156128aa57506040513d6000823e601f3d908101601f191682016040526128a79190810190612fdf565b60015b6128b357612933565b6000826000815181106128c257fe5b6020026020010151836001815181106128d757fe5b60200260200101510390508663ffffffff168160060b816128f457fe5b05945060008160060b12801561291e57508663ffffffff168160060b8161291757fe5b0760060b15155b1561292b57600019909401935b600195505050505b509250929050565b60008061294786612a2d565b90506001600160801b036001600160a01b038216116129b6576001600160a01b038082168002908481169086161061299657612991600160c01b876001600160801b031683612d55565b6129ae565b6129ae81876001600160801b0316600160c01b612d55565b925050612a24565b60006129d06001600160a01b03831680600160401b612d55565b9050836001600160a01b0316856001600160a01b031610612a0857612a03600160801b876001600160801b031683612d55565b612a20565b612a2081876001600160801b0316600160801b612d55565b9250505b50949350505050565b60008060008360020b12612a44578260020b612a4c565b8260020b6000035b9050620d89e8811115612a8a576040805162461bcd60e51b81526020600482015260016024820152601560fa1b604482015290519081900360640190fd5b600060018216612a9e57600160801b612ab0565b6ffffcb933bd6fad37aa2d162d1a5940015b6001600160881b031690506002821615612ada576ffff97272373d413259a46990580e213a0260801c5b6004821615612af9576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615612b18576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615612b37576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615612b56576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615612b75576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615612b94576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615612bb4576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615612bd4576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615612bf4576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615612c14576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615612c34576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615612c54576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615612c74576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615612c94576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615612cb5576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615612cd5576e5d6af8dedb81196699c329225ee6040260801c5b62040000821615612cf4576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615612d11576b048a170391f7dc42444e8fa20260801c5b60008460020b1315612d2c578060001981612d2857fe5b0490505b640100000000810615612d40576001612d43565b60005b60ff16602082901c0192505050919050565b6000808060001985870986860292508281109083900303905080612d8b5760008411612d8057600080fd5b50829004905061009c565b808411612d9757600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b60405180604001604052806002906020820280368337509192915050565b60405180606001604052806000815260200160008152602001600081525090565b600082601f830112612e53578081fd5b81516020612e68612e6383613619565b6135f6565b8281528181019085830183850287018401881015612e84578586fd5b855b85811015612eab578151612e9981613666565b84529284019290840190600101612e86565b5090979650505050505050565b80516001600160501b038116811461059b57600080fd5b60008060408385031215612ee1578182fd5b8235612eec81613666565b91506020830135612efc81613666565b809150509250929050565b600080600060608486031215612f1b578081fd5b8335612f2681613666565b92506020840135612f3681613666565b929592945050506040919091013590565b60006020808385031215612f59578182fd5b82516001600160401b03811115612f6e578283fd5b8301601f81018513612f7e578283fd5b8051612f8c612e6382613619565b8181528381019083850185840285018601891015612fa8578687fd5b8694505b83851015612fd3578051612fbf81613666565b835260019490940193918501918501612fac565b50979650505050505050565b60008060408385031215612ff1578182fd5b82516001600160401b0380821115613007578384fd5b818501915085601f83011261301a578384fd5b8151602061302a612e6383613619565b82815281810190858301838502870184018b1015613046578889fd5b8896505b848710156130765780518060060b811461306257898afd5b83526001969096019591830191830161304a565b509188015191965090935050508082111561308f578283fd5b5061309c85828601612e43565b9150509250929050565b6000604082840312156130b7578081fd5b82601f8301126130c5578081fd5b604051604081018181106001600160401b03821117156130e157fe5b80604052508083856040860111156130f7578384fd5b835b60028110156131185781518352602092830192909101906001016130f9565b509195945050505050565b60006020808385031215613135578182fd5b82516001600160401b0381111561314a578283fd5b8301601f8101851361315a578283fd5b8051613168612e6382613619565b8181528381019083850185840285018601891015613184578687fd5b8694505b83851015612fd3578051835260019490940193918501918501613188565b600060208083850312156131b8578182fd5b82516001600160401b03808211156131ce578384fd5b90840190604082870312156131e1578384fd5b6040516040810181811083821117156131f657fe5b604052825161320481613666565b81528284015182811115613216578586fd5b80840193505086601f84011261322a578485fd5b82518281111561323657fe5b613248601f8201601f191686016135f6565b9250808352878582860101111561325d578586fd5b61326c81868501878701613636565b5092830152509392505050565b60006020828403121561328a578081fd5b5051919050565b600080600080600060a086880312156132a8578283fd5b6132b186612eb8565b94506020860151935060408601519250606086015191506132d460808701612eb8565b90509295509295909350565b6000602082840312156132f1578081fd5b815160ff81168114610083578182fd5b6000815180845260208085019450808401835b8381101561333057815187529582019590820190600101613314565b509495945050505050565b60008151808452613353816020860160208601613636565b601f01601f19169290920160200192915050565b6000602082526100836020830184613301565b60006040825261338d6040830185613301565b8281036020840152610dcf818561333b565b6000608082526133b26080830187613301565b85602084015282810360408401526133ca8186613301565b90508281036060840152610fa4818561333b565b6020808252825182820181905260009190848201906040850190845b8181101561341c57835163ffffffff16835292840192918401916001016133fa565b50909695505050505050565b60208082526026908201527f436f6e766572743a204e6f7420612077686974656c6973746564204375727665604082015265103837b7b61760d11b606082015260800190565b602080825260029082015261042560f41b604082015260600190565b6020808252601c908201527f4f7261636c653a20546f6b656e206e6f7420737570706f727465642e00000000604082015260600190565b6020808252601a908201527f436f6e766572743a20555344204f7261636c65206661696c6564000000000000604082015260600190565b6020808252600b908201526a6e6f742076657374696e6760a81b604082015260600190565b6020808252601d908201527f436f6e766572743a20546f6b656e73206e6f7420737570706f72746564000000604082015260600190565b6020808252601190820152702132b0b7103737ba1034b7102bb2b6361760791b604082015260600190565b60208082526018908201527750726963653a20436f6e76657267656e63652066616c736560401b604082015260600190565b90815260200190565b9182526001600160a01b0316602082015260400190565b918252600f0b602082015260400190565b6001600160501b0391909116815260200190565b6040518181016001600160401b038111828210171561361157fe5b604052919050565b60006001600160401b0382111561362c57fe5b5060209081020190565b60005b83811015613651578181015183820152602001613639565b83811115613660576000848401525b50505050565b6001600160a01b038116811461367b57600080fd5b5056fe000000000000000000000000bea0000029ad1c77d3d5d23ba2d8893db9d1efab536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f770000000000000000000000001bea0050e63e05fbb5d8ba2f10cf5800b62244490000000000000000000000001bea3ccd22f4ebd3d37d731ba31eeca95713716da2646970667358221220d414f9e558fcad05140740fad1b438579e5b482ae04dff963a233a6f9d00b94a64736f6c63430007060033
Deployed Bytecode
0x608060405234801561001057600080fd5b50600436106100365760003560e01c806324dd285c1461003b5780634aa0665214610064575b600080fd5b61004e610049366004612ecf565b610077565b60405161005b91906135b1565b60405180910390f35b61004e610072366004612f07565b61008c565b600061008383836100a3565b90505b92915050565b60006100998484846102b5565b90505b9392505050565b60006001600160a01b03831673c9c32cd16bf7efb85ff14e0c8603cc90f6f2ee491480156100e757506001600160a01b03821660008051602061367f833981519152145b156101105761010973c9c32cd16bf7efb85ff14e0c8603cc90f6f2ee496104f5565b9050610086565b816001600160a01b0316836001600160a01b031614156101335750600019610086565b6001600160a01b03831660008051602061367f8339815191521480156101665750610166826001600160a01b03166105a0565b1561017457610109826105e5565b610186836001600160a01b03166105a0565b80156101a857506001600160a01b03821660008051602061367f833981519152145b156101b657610109836105f7565b6001600160a01b0383166000805160206136e08339815191521415610226576001600160a01b0382166000805160206136c083398151915214156101fc57610109610986565b6102046109b9565b6001600160a01b0316826001600160a01b031614156102265750600019610086565b6001600160a01b0383166000805160206136c08339815191521415610294576001600160a01b0382166000805160206136e0833981519152141561026c57610109610a3c565b6001600160a01b03821660008051602061367f83398151915214156102945750600019610086565b60405162461bcd60e51b81526004016102ac9061351d565b60405180910390fd5b60006001600160a01b03841673c9c32cd16bf7efb85ff14e0c8603cc90f6f2ee491480156102f957506001600160a01b03831660008051602061367f833981519152145b156103235761031c73c9c32cd16bf7efb85ff14e0c8603cc90f6f2ee4983610a69565b905061009c565b6001600160a01b0384166000805160206136e083398151915214801561035f57506001600160a01b0383166000805160206136c0833981519152145b1561036d5761031c82610aea565b6001600160a01b0384166000805160206136c08339815191521480156103a957506001600160a01b0383166000805160206136e0833981519152145b156103b75761031c82610bd3565b826001600160a01b0316846001600160a01b031614156103d857508061009c565b6001600160a01b03841660008051602061367f83398151915214801561040b575061040b836001600160a01b03166105a0565b1561041a5761031c8383610c73565b61042c846001600160a01b03166105a0565b801561044e57506001600160a01b03831660008051602061367f833981519152145b1561045d5761031c8483610dd8565b6001600160a01b0384166000805160206136c083398151915214801561049957506001600160a01b03831660008051602061367f833981519152145b156104a85761031c8483610e17565b6001600160a01b0384166000805160206136e08339815191521480156104e657506104d16109b9565b6001600160a01b0316836001600160a01b0316145b156102945761031c8483610e17565b600080826001600160a01b03166314f059796040518163ffffffff1660e01b8152600401604080518083038186803b15801561053057600080fd5b505afa158015610544573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061056891906130a6565b905060006105768483610e94565b8251909150811061058c5760009250505061059b565b6105968282610edc565b925050505b919050565b6000806105ab610faf565b6001600160a01b03841660009081526039909101602052604090205460e01b6001600160e01b03191663c84c772760e01b14915050919050565b60006105f082610fb4565b5092915050565b600080826001600160a01b0316639d63848a6040518163ffffffff1660e01b815260040160006040518083038186803b15801561063357600080fd5b505afa158015610647573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261066f9190810190612f47565b90506000836001600160a01b0316630902f1ac6040518163ffffffff1660e01b815260040160006040518083038186803b1580156106ac57600080fd5b505afa1580156106c0573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526106e89190810190613123565b90506000846001600160a01b03166310dd08306040518163ffffffff1660e01b815260040160006040518083038186803b15801561072557600080fd5b505afa158015610739573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261076191908101906131a6565b905060008060006107718661122c565b925092509250806107945760405162461bcd60e51b81526004016102ac906134c1565b835160208501516040516316a1119f60e21b81526000926001600160a01b031691635a84467c916107cd918a9188918a9160040161339f565b60206040518083038186803b1580156107e557600080fd5b505afa1580156107f9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061081d9190613279565b90508086848151811061082c57fe5b60200260200101511161084957600097505050505050505061059b565b845160208601516040516253057f60e61b81526000926001600160a01b0316916314c15fc09161087d918b9160040161337a565b60206040518083038186803b15801561089557600080fd5b505afa1580156108a9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108cd9190613279565b9050818785815181106108dc57fe5b60200260200101818152505061097886600001516001600160a01b03166314c15fc08989602001516040518363ffffffff1660e01b815260040161092192919061337a565b60206040518083038186803b15801561093957600080fd5b505afa15801561094d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109719190613279565b8290611249565b9a9950505050505050505050565b6000806109996109946109b9565b6105f7565b90506109b36000805160206136e0833981519152826112a6565b91505090565b6000806109c4610faf565b6000805160206136e0833981519152600090815260408083016020529020549091506001600160a01b031615610a21576000805160206136e0833981519152600090815260408083016020529020546001600160a01b03166109b3565b73bea0000113b0d182f4064c86b71c315389e4715d91505090565b600080610a4f610a4a6109b9565b6105e5565b90506109b36000805160206136c0833981519152826112a6565b60405163cc2b27d760e01b81526000906001600160a01b0384169063cc2b27d790610a9a90859085906004016135d1565b60206040518083038186803b158015610ab257600080fd5b505afa158015610ac6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100839190613279565b600080610b846000805160206136e0833981519152846000805160206136e08339815191526001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b158015610b4757600080fd5b505afa158015610b5b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b7f9190613279565b61135e565b9050610b97610b916109b9565b82610dd8565b915061009c610ba4611399565b610bcd610baf611431565b610bc76000805160206136c0833981519152876112a6565b906114e4565b9061153d565b600080610c306000805160206136c0833981519152846000805160206136c08339815191526001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b158015610b4757600080fd5b9050610c43610c3d6109b9565b82610c73565b915061009c610c50611431565b610bcd610c5b611399565b610bc76000805160206136e0833981519152876112a6565b600080836001600160a01b0316639d63848a6040518163ffffffff1660e01b815260040160006040518083038186803b158015610caf57600080fd5b505afa158015610cc3573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610ceb9190810190612f47565b9050600081516001600160401b0381118015610d0657600080fd5b50604051908082528060200260200182016040528015610d30578160200160208202803683370190505b5090508381610d3e846115a4565b81518110610d4857fe5b6020908102919091010152604051638974eb0f60e01b81526001600160a01b03861690638974eb0f90610d7f908490600401613367565b60206040518083038186803b158015610d9757600080fd5b505afa158015610dab573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dcf9190613279565b95945050505050565b6040516308cfce0f60e41b81526000906001600160a01b03841690638cfce0f090610a9a90859060008051602061367f833981519152906004016135ba565b60006100838383856001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b158015610e5757600080fd5b505afa158015610e6b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e8f9190613279565b611610565b60006001600160a01b03831673c9c32cd16bf7efb85ff14e0c8603cc90f6f2ee491415610ec457610109826116ef565b60405162461bcd60e51b81526004016102ac90613428565b600080610ee761178c565b6001600160a01b03166376a2f0f06040518163ffffffff1660e01b815260040160206040518083038186803b158015610f1f57600080fd5b505afa158015610f33573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f579190613279565b90506000610f64856117a4565b90506000610f7282846117bb565b90506000610f888688835b602002015190611249565b9050610f96818884876118c7565b9050610fa481888487611a30565b979650505050505050565b600090565b6000806000836001600160a01b0316639d63848a6040518163ffffffff1660e01b815260040160006040518083038186803b158015610ff257600080fd5b505afa158015611006573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261102e9190810190612f47565b90506000846001600160a01b0316630902f1ac6040518163ffffffff1660e01b815260040160006040518083038186803b15801561106b57600080fd5b505afa15801561107f573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526110a79190810190613123565b90506000856001600160a01b03166310dd08306040518163ffffffff1660e01b815260040160006040518083038186803b1580156110e457600080fd5b505afa1580156110f8573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261112091908101906131a6565b90506060600061112f8561122c565b9097509092509050806111545760405162461bcd60e51b81526004016102ac906134c1565b825160208401516040516316a1119f60e21b81526000926001600160a01b031691635a84467c9161118d9189918c91899160040161339f565b60206040518083038186803b1580156111a557600080fd5b505afa1580156111b9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111dd9190613279565b90508487815181106111eb57fe5b602002602001015181116112085760009750505050505050611227565b84878151811061121457fe5b6020026020010151810397505050505050505b915091565b606060008061123c846000611afa565b9250925092509193909250565b6000828211156112a0576040805162461bcd60e51b815260206004820152601e60248201527f536166654d6174683a207375627472616374696f6e206f766572666c6f770000604482015290519081900360640190fd5b50900390565b6000806112b1610faf565b9050611356816040016000866001600160a01b03166001600160a01b0316815260200190815260200160002060010154610bcd85876001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561131e57600080fd5b505afa158015611332573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bc79190613279565b949350505050565b600080611369610faf565b6001600160a01b03861660009081526040808301602052902060010154909150610dcf908490610bcd90876114e4565b6000806113a4610faf565b90506109b36113b1611c3f565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156113e957600080fd5b505afa1580156113fd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114219190613279565b610bcd8360480154610bc7611c51565b60008061143c610faf565b90506109b3611449611c58565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561148157600080fd5b505afa158015611495573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114b99190613279565b6000805160206136c083398151915260009081526040808501602052902060010154610bcd90620f42405b6000826114f357506000610086565b8282028284828161150057fe5b04146100835760405162461bcd60e51b815260040180806020018281038252602181526020018061369f6021913960400191505060405180910390fd5b6000808211611593576040805162461bcd60e51b815260206004820152601a60248201527f536166654d6174683a206469766973696f6e206279207a65726f000000000000604482015290519081900360640190fd5b81838161159c57fe5b049392505050565b60005b81518110156115f8578181815181106115bc57fe5b60200260200101516001600160a01b031660008051602061367f8339815191526001600160a01b031614156115f05761059b565b6001016115a7565b60405162461bcd60e51b81526004016102ac90613554565b600061161b84611c6a565b6116375760405162461bcd60e51b81526004016102ac906134f8565b6000611641610faf565b905060006001600160a01b0386166000805160206136e0833981519152146116705761166b611c9a565b611679565b61167984611d21565b6001600160a01b03871660009081526040808501602052902060010154909150816116b3576116ac85610bcd83896114e4565b93506116d9565b6116d685610bcd88610bc786610bcd8960480154886114e490919063ffffffff16565b93505b808411156116e5578093505b5050509392505050565b60006100866c0c9f2c9cd04674edea40000000610bcd61170d611d47565b6001600160a01b031663bb7b8b806040518163ffffffff1660e01b815260040160206040518083038186803b15801561174557600080fd5b505afa158015611759573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061177d9190613279565b8560015b6020020151906114e4565b73c9c32cd16bf7efb85ff14e0c8603cc90f6f2ee4990565b6117ac612e04565b6100868264e8d4a51000611d5f565b6000806000805b60028110156117e9578581600281106117d757fe5b602002015192909201916001016117c2565b50816117fa57600092505050610086565b90915081906002840260005b6101008110156118ae578460005b600281101561184657600289826002811061182b57fe5b6020020151028783028161183b57fe5b049150600101611814565b50859350600381026064606319850186020401866002830260648689020401028161186d57fe5b04955083861180156118825750600184870311155b15611891575050505050610086565b6001868503116118a5575050505050610086565b50600101611806565b5060405162461bcd60e51b81526004016102ac9061357f565b6000806118d3856117a4565b905060006118ea6118e5888884610f7d565b611de9565b9050600061191c60405180604001604052808481526020018560016002811061190f57fe5b60200201519052866117bb565b9050611926612e04565b60006119418461193b8a610bcd878a87611781565b90611249565b90506119696402540be400611959621e8480846114e4565b8161196057fe5b04866000610f7d565b825261198661197e89610bcd86896001611781565b866001610f7d565b90506119ae6402540be40061199e621e8480846114e4565b816119a557fe5b04866001610f7d565b602083015260006119c188828587611dfa565b905060006119d0828583610f7d565b90506119e56119e0826001611249565b611ee3565b905060006119f76119e0888a84610f7d565b9050611a1f611a186402540be400610bcd64012a05f200610bc78688611249565b8290611ef4565b9d9c50505050505050505050505050565b6000611a3d858583610f7d565b84526000611a4a856117a4565b90506000611a5882856117bb565b90506000611a668683611249565b9050611aee86610bcd611a7761178c565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b158015611aaf57600080fd5b505afa158015611ac3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ae79190613279565b84906114e4565b98975050505050505050565b60606000806001905084516001600160401b0381118015611b1a57600080fd5b50604051908082528060200260200182016040528015611b44578160200160208202803683370190505b509250600019915060005b8551811015611c1557858181518110611b6457fe5b60200260200101516001600160a01b031660008051602061367f8339815191526001600160a01b03161415611bb757809250620f4240848281518110611ba657fe5b602002602001018181525050611c0d565b611bd4868281518110611bc657fe5b602002602001015186611f4e565b848281518110611be057fe5b602002602001018181525050838181518110611bf857fe5b602002602001015160001415611c0d57600091505b600101611b4f565b50600019821415611c385760405162461bcd60e51b81526004016102ac90613554565b9250925092565b6000805160206136e083398151915290565b621cc1b090565b6000805160206136c083398151915290565b600080611c75610faf565b6001600160a01b03938416600090815260409182016020522054909216151592915050565b6000611d1c611ca7611c3f565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b158015611cdf57600080fd5b505afa158015611cf3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d179190613279565b611d21565b905090565b600080611d37620f4240610bcd85610bc7611ff5565b620f424090819004029392505050565b73bebc44782c7db0a1a60cb6fe97d0b483032ff1c790565b611d67612e04565b6100838383611d74611d47565b6001600160a01b031663bb7b8b806040518163ffffffff1660e01b815260040160206040518083038186803b158015611dac57600080fd5b505afa158015611dc0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611de49190613279565b611ffc565b60006100868264e8d4a510006114e4565b60008080808460028902825b6002811015611e5157898114611e2e57888160028110611e2257fe5b60200201519450611e33565b611e49565b948401946002850283890281611e4557fe5b0492505b600101611e06565b506002810260648884020281611e6357fe5b0491506000816064890281611e7457fe5b048601905087965060005b60ff8110156118ae57879450888289600202010384898a020181611e9f57fe5b0497508488118015611eb45750600185890311155b15611ec55750505050505050611356565b600188860311611edb5750505050505050611356565b600101611e7f565b60006100868264e8d4a5100061153d565b600082820183811015610083576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b60006001600160a01b03831673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc21415611fad576000611f8083612036565b905080611f91576000915050610086565b611fa569d3c21bcecceda10000008261153d565b915050610086565b6001600160a01b038316737f39c581f595b53c5cb19bd0b3f8da6c935e2ca01415611fdd576000611f8083612085565b60405162461bcd60e51b81526004016102ac9061348a565b620818ba90565b612004612e04565b61201083856000611781565b815261202a670de0b6b3a7640000610bcd84876001611781565b60208201529392505050565b60008082116120645761205f735f4ec3df9cbd43714fe2740f5e3616155c5b84196138406120a3565b610086565b610086735f4ec3df9cbd43714fe2740f5e3616155c5b841961384084612201565b6000610086620f4240610bcd61209a85612036565b610bc78661244c565b6000808390506000816001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156120e457600080fd5b505afa925050508015612114575060408051601f3d908101601f19168201909252612111918101906132e0565b60015b61212357600092505050610086565b9050816001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a06040518083038186803b15801561215e57600080fd5b505afa92505050801561218e575060408051601f3d908101601f1916820190925261218b91810190613291565b60015b61219d57600092505050610086565b6001600160501b0385166121bb576000975050505050505050610086565b6121c78285428c612625565b156121dc576000975050505050505050610086565b6121f360ff8716600a0a610bcd86620f42406114e4565b975050505050505050610086565b6000808490506000816001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b15801561224257600080fd5b505afa925050508015612272575060408051601f3d908101601f1916820190925261226f918101906132e0565b60015b6122815760009250505061009c565b9050816001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a06040518083038186803b1580156122bc57600080fd5b505afa9250505080156122ec575060408051601f3d908101601f191682019092526122e991810190613291565b60015b6122fb5760009250505061009c565b6001600160501b03851661231957600097505050505050505061009c565b6123258285428d612625565b1561233a57600097505050505050505061009c565b612342612e22565b61234c428b611249565b60208201819052831161237f5761237060ff8816600a0a610bcd87620f42406114e4565b9850505050505050505061009c565b4260408201525b806020015183111561240b576123be6123b66123af85846040015161124990919063ffffffff16565b87906114e4565b825190611ef4565b815260408101839052600019909501946123d88887612669565b80945081965050506123f0838683604001518e612625565b156124065760009850505050505050505061009c565b612386565b61242c6123b66123af8360200151846040015161124990919063ffffffff16565b808252612370908b90610bcd9060ff8b16600a0a908290620f42406114e4565b600080821561247c576124777386392dc19c0b719886221c78ab11eb8cf5c528126205460085612201565b61249d565b61249d7386392dc19c0b719886221c78ab11eb8cf5c52812620546006120a3565b9050806124ae57600091505061059b565b6000737f39c581f595b53c5cb19bd0b3f8da6c935e2ca06001600160a01b031663035faf826040518163ffffffff1660e01b815260040160206040518083038186803b1580156124fd57600080fd5b505afa158015612511573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125359190613279565b9050612548620f4240610bcd84846114e4565b915063ffffffff8411156125615760009250505061059b565b60006125c385156125725785612576565b6103845b73109830a1aaad605bbf02a9dfa7b0b92ec2fb7daa737f39c581f595b53c5cb19bd0b3f8da6c935e2ca073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2670de0b6b3a7640000612707565b9050806125d6576000935050505061059b565b662386f26fc100006125e88483612736565b101561261d576125fd6002610bcd8584611ef4565b93508184111561260b578193505b61261a8464e8d4a5100061153d565b93505b505050919050565b600084158061263357508285115b1561264057506001611356565b8161264b8487611249565b111561265957506001611356565b6000841361135657506001611356565b600080836001600160a01b0316639a6fc8f5846040518263ffffffff1660e01b815260040161269891906135e2565b60a06040518083038186803b1580156126b057600080fd5b505afa9250505080156126e0575060408051601f3d908101601f191682019092526126dd91810190613291565b60015b6126f1575060001990506000612700565b50919450909250612700915050565b9250929050565b6000806000612716878961279e565b915091508161272a57600092505050610dcf565b611aee8185888861293b565b60008183141561274857506000610086565b818310156127775761276682610bcd85670de0b6b3a76400006114e4565b670de0b6b3a7640000039050610086565b61278d83610bcd84670de0b6b3a76400006114e4565b670de0b6b3a7640000039392505050565b60008063ffffffff83166127c45760405162461bcd60e51b81526004016102ac9061346e565b60408051600280825260608201835260009260208301908036833701905050905083816000815181106127f357fe5b602002602001019063ffffffff16908163ffffffff168152505060008160018151811061281c57fe5b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526001600160a01b0386169063883bdbfd9061285d9084906004016133de565b60006040518083038186803b15801561287557600080fd5b505afa9250505080156128aa57506040513d6000823e601f3d908101601f191682016040526128a79190810190612fdf565b60015b6128b357612933565b6000826000815181106128c257fe5b6020026020010151836001815181106128d757fe5b60200260200101510390508663ffffffff168160060b816128f457fe5b05945060008160060b12801561291e57508663ffffffff168160060b8161291757fe5b0760060b15155b1561292b57600019909401935b600195505050505b509250929050565b60008061294786612a2d565b90506001600160801b036001600160a01b038216116129b6576001600160a01b038082168002908481169086161061299657612991600160c01b876001600160801b031683612d55565b6129ae565b6129ae81876001600160801b0316600160c01b612d55565b925050612a24565b60006129d06001600160a01b03831680600160401b612d55565b9050836001600160a01b0316856001600160a01b031610612a0857612a03600160801b876001600160801b031683612d55565b612a20565b612a2081876001600160801b0316600160801b612d55565b9250505b50949350505050565b60008060008360020b12612a44578260020b612a4c565b8260020b6000035b9050620d89e8811115612a8a576040805162461bcd60e51b81526020600482015260016024820152601560fa1b604482015290519081900360640190fd5b600060018216612a9e57600160801b612ab0565b6ffffcb933bd6fad37aa2d162d1a5940015b6001600160881b031690506002821615612ada576ffff97272373d413259a46990580e213a0260801c5b6004821615612af9576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615612b18576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615612b37576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615612b56576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615612b75576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615612b94576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615612bb4576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615612bd4576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615612bf4576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615612c14576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615612c34576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615612c54576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615612c74576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615612c94576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615612cb5576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615612cd5576e5d6af8dedb81196699c329225ee6040260801c5b62040000821615612cf4576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615612d11576b048a170391f7dc42444e8fa20260801c5b60008460020b1315612d2c578060001981612d2857fe5b0490505b640100000000810615612d40576001612d43565b60005b60ff16602082901c0192505050919050565b6000808060001985870986860292508281109083900303905080612d8b5760008411612d8057600080fd5b50829004905061009c565b808411612d9757600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b60405180604001604052806002906020820280368337509192915050565b60405180606001604052806000815260200160008152602001600081525090565b600082601f830112612e53578081fd5b81516020612e68612e6383613619565b6135f6565b8281528181019085830183850287018401881015612e84578586fd5b855b85811015612eab578151612e9981613666565b84529284019290840190600101612e86565b5090979650505050505050565b80516001600160501b038116811461059b57600080fd5b60008060408385031215612ee1578182fd5b8235612eec81613666565b91506020830135612efc81613666565b809150509250929050565b600080600060608486031215612f1b578081fd5b8335612f2681613666565b92506020840135612f3681613666565b929592945050506040919091013590565b60006020808385031215612f59578182fd5b82516001600160401b03811115612f6e578283fd5b8301601f81018513612f7e578283fd5b8051612f8c612e6382613619565b8181528381019083850185840285018601891015612fa8578687fd5b8694505b83851015612fd3578051612fbf81613666565b835260019490940193918501918501612fac565b50979650505050505050565b60008060408385031215612ff1578182fd5b82516001600160401b0380821115613007578384fd5b818501915085601f83011261301a578384fd5b8151602061302a612e6383613619565b82815281810190858301838502870184018b1015613046578889fd5b8896505b848710156130765780518060060b811461306257898afd5b83526001969096019591830191830161304a565b509188015191965090935050508082111561308f578283fd5b5061309c85828601612e43565b9150509250929050565b6000604082840312156130b7578081fd5b82601f8301126130c5578081fd5b604051604081018181106001600160401b03821117156130e157fe5b80604052508083856040860111156130f7578384fd5b835b60028110156131185781518352602092830192909101906001016130f9565b509195945050505050565b60006020808385031215613135578182fd5b82516001600160401b0381111561314a578283fd5b8301601f8101851361315a578283fd5b8051613168612e6382613619565b8181528381019083850185840285018601891015613184578687fd5b8694505b83851015612fd3578051835260019490940193918501918501613188565b600060208083850312156131b8578182fd5b82516001600160401b03808211156131ce578384fd5b90840190604082870312156131e1578384fd5b6040516040810181811083821117156131f657fe5b604052825161320481613666565b81528284015182811115613216578586fd5b80840193505086601f84011261322a578485fd5b82518281111561323657fe5b613248601f8201601f191686016135f6565b9250808352878582860101111561325d578586fd5b61326c81868501878701613636565b5092830152509392505050565b60006020828403121561328a578081fd5b5051919050565b600080600080600060a086880312156132a8578283fd5b6132b186612eb8565b94506020860151935060408601519250606086015191506132d460808701612eb8565b90509295509295909350565b6000602082840312156132f1578081fd5b815160ff81168114610083578182fd5b6000815180845260208085019450808401835b8381101561333057815187529582019590820190600101613314565b509495945050505050565b60008151808452613353816020860160208601613636565b601f01601f19169290920160200192915050565b6000602082526100836020830184613301565b60006040825261338d6040830185613301565b8281036020840152610dcf818561333b565b6000608082526133b26080830187613301565b85602084015282810360408401526133ca8186613301565b90508281036060840152610fa4818561333b565b6020808252825182820181905260009190848201906040850190845b8181101561341c57835163ffffffff16835292840192918401916001016133fa565b50909695505050505050565b60208082526026908201527f436f6e766572743a204e6f7420612077686974656c6973746564204375727665604082015265103837b7b61760d11b606082015260800190565b602080825260029082015261042560f41b604082015260600190565b6020808252601c908201527f4f7261636c653a20546f6b656e206e6f7420737570706f727465642e00000000604082015260600190565b6020808252601a908201527f436f6e766572743a20555344204f7261636c65206661696c6564000000000000604082015260600190565b6020808252600b908201526a6e6f742076657374696e6760a81b604082015260600190565b6020808252601d908201527f436f6e766572743a20546f6b656e73206e6f7420737570706f72746564000000604082015260600190565b6020808252601190820152702132b0b7103737ba1034b7102bb2b6361760791b604082015260600190565b60208082526018908201527750726963653a20436f6e76657267656e63652066616c736560401b604082015260600190565b90815260200190565b9182526001600160a01b0316602082015260400190565b918252600f0b602082015260400190565b6001600160501b0391909116815260200190565b6040518181016001600160401b038111828210171561361157fe5b604052919050565b60006001600160401b0382111561362c57fe5b5060209081020190565b60005b83811015613651578181015183820152602001613639565b83811115613660576000848401525b50505050565b6001600160a01b038116811461367b57600080fd5b5056fe000000000000000000000000bea0000029ad1c77d3d5d23ba2d8893db9d1efab536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f770000000000000000000000001bea0050e63e05fbb5d8ba2f10cf5800b62244490000000000000000000000001bea3ccd22f4ebd3d37d731ba31eeca95713716da2646970667358221220d414f9e558fcad05140740fad1b438579e5b482ae04dff963a233a6f9d00b94a64736f6c63430007060033
Loading...
Loading
Loading...
Loading
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.