Overview
ETH Balance
0 ETH
Eth Value
$0.00More Info
Private Name Tags
ContractCreator
View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Loading...
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Contract Name:
ConvertFacet
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 {C} from "contracts/C.sol"; import {LibSilo} from "contracts/libraries/Silo/LibSilo.sol"; import {LibTokenSilo} from "contracts/libraries/Silo/LibTokenSilo.sol"; import {LibSafeMath32} from "contracts/libraries/LibSafeMath32.sol"; import {ReentrancyGuard} from "../ReentrancyGuard.sol"; import {LibBytes} from "contracts/libraries/LibBytes.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {LibConvert} from "contracts/libraries/Convert/LibConvert.sol"; import {LibGerminate} from "contracts/libraries/Silo/LibGerminate.sol"; /** * @author Publius, Brean, DeadManWalking * @title ConvertFacet handles converting Deposited assets within the Silo. **/ contract ConvertFacet is ReentrancyGuard { using SafeMath for uint256; using SafeCast for uint256; using LibSafeMath32 for uint32; event Convert( address indexed account, address fromToken, address toToken, uint256 fromAmount, uint256 toAmount ); event RemoveDeposit( address indexed account, address indexed token, int96 stem, uint256 amount, uint256 bdv ); event RemoveDeposits( address indexed account, address indexed token, int96[] stems, uint256[] amounts, uint256 amount, uint256[] bdvs ); /** * @notice convert allows a user to convert a deposit to another deposit, * given that the conversion is supported by the ConvertFacet. * For example, a user can convert LP into Bean, only when beanstalk is below peg, * or convert beans into LP, only when beanstalk is above peg. * @param convertData input parameters to determine the conversion type. * @param stems the stems of the deposits to convert * @param amounts the amounts within each deposit to convert * @return toStem the new stems of the converted deposit * @return fromAmount the amount of tokens converted from * @return toAmount the amount of tokens converted to * @return fromBdv the bdv of the deposits converted from * @return toBdv the bdv of the deposit converted to */ function convert( bytes calldata convertData, int96[] memory stems, uint256[] memory amounts ) external payable nonReentrant returns (int96 toStem, uint256 fromAmount, uint256 toAmount, uint256 fromBdv, uint256 toBdv) { address toToken; address fromToken; uint256 grownStalk; (toToken, fromToken, toAmount, fromAmount) = LibConvert.convert(convertData); require(fromAmount > 0, "Convert: From amount is 0."); LibSilo._mow(msg.sender, fromToken); LibSilo._mow(msg.sender, toToken); (grownStalk, fromBdv) = _withdrawTokens( fromToken, stems, amounts, fromAmount ); // calculate the bdv of the new deposit uint256 newBdv = LibTokenSilo.beanDenominatedValue(toToken, toAmount); toBdv = newBdv > fromBdv ? newBdv : fromBdv; toStem = _depositTokensForConvert(toToken, toAmount, toBdv, grownStalk); emit Convert(msg.sender, fromToken, toToken, fromAmount, toAmount); } /** * @notice removes the deposits from msg.sender and returns the * grown stalk and bdv removed. * * @dev if a user inputs a stem of a deposit that is `germinating`, * the function will omit that deposit. This is due to the fact that * germinating deposits can be manipulated and skip the germination process. */ function _withdrawTokens( address token, int96[] memory stems, uint256[] memory amounts, uint256 maxTokens ) internal returns (uint256, uint256) { require( stems.length == amounts.length, "Convert: stems, amounts are diff lengths." ); LibSilo.AssetsRemoved memory a; uint256 depositBDV; uint256 i = 0; // a bracket is included here to avoid the "stack too deep" error. { uint256[] memory bdvsRemoved = new uint256[](stems.length); uint256[] memory depositIds = new uint256[](stems.length); // get germinating stem and stemTip for the token LibGerminate.GermStem memory germStem = LibGerminate.getGerminatingStem(token); while ((i < stems.length) && (a.active.tokens < maxTokens)) { // skip any stems that are germinating, due to the ability to // circumvent the germination process. if (germStem.germinatingStem <= stems[i]) { i++; continue; } if (a.active.tokens.add(amounts[i]) >= maxTokens) amounts[i] = maxTokens.sub(a.active.tokens); depositBDV = LibTokenSilo.removeDepositFromAccount( msg.sender, token, stems[i], amounts[i] ); bdvsRemoved[i] = depositBDV; a.active.stalk = a.active.stalk.add( LibSilo.stalkReward( stems[i], germStem.stemTip, depositBDV.toUint128() ) ); a.active.tokens = a.active.tokens.add(amounts[i]); a.active.bdv = a.active.bdv.add(depositBDV); depositIds[i] = uint256(LibBytes.packAddressAndStem( token, stems[i] )); i++; } // if the loop is exited early, set the remaining amounts to 0. // `i` is not reinitialized and uses the value from the loop. for (i; i < stems.length; ++i) amounts[i] = 0; emit RemoveDeposits( msg.sender, token, stems, amounts, a.active.tokens, bdvsRemoved ); emit LibSilo.TransferBatch( msg.sender, msg.sender, address(0), depositIds, amounts ); } require( a.active.tokens == maxTokens, "Convert: Not enough tokens removed." ); LibTokenSilo.decrementTotalDeposited(token, a.active.tokens, a.active.bdv); // all deposits converted are not germinating. LibSilo.burnActiveStalk( msg.sender, a.active.stalk.add(a.active.bdv.mul(s.ss[token].stalkIssuedPerBdv)) ); return (a.active.stalk, a.active.bdv); } /** * @notice deposits token into the silo with the given grown stalk. * @param token the token to deposit * @param amount the amount of tokens to deposit * @param bdv the bean denominated value of the deposit * @param grownStalk the amount of grown stalk retained to issue to the new deposit. * * @dev there are cases where a convert may cause the new deposit to be partially germinating, * if the convert goes from a token with a lower amount of seeds to a higher amount of seeds. * We accept this as a tradeoff to avoid additional complexity. */ function _depositTokensForConvert( address token, uint256 amount, uint256 bdv, uint256 grownStalk ) internal returns (int96 stem) { require(bdv > 0 && amount > 0, "Convert: BDV or amount is 0."); LibGerminate.Germinate germ; // calculate the stem and germination state for the new deposit. (stem, germ) = LibTokenSilo.calculateStemForTokenFromGrownStalk(token, grownStalk, bdv); // increment totals based on germination state, // as well as issue stalk to the user. // if the deposit is germinating, only the initial stalk of the deposit is germinating. // the rest is active stalk. if (germ == LibGerminate.Germinate.NOT_GERMINATING) { LibTokenSilo.incrementTotalDeposited(token, amount, bdv); LibSilo.mintActiveStalk( msg.sender, bdv.mul(LibTokenSilo.stalkIssuedPerBdv(token)).add(grownStalk) ); } else { LibTokenSilo.incrementTotalGerminating(token, amount, bdv, germ); LibSilo.mintGerminatingStalk(msg.sender, bdv.mul(LibTokenSilo.stalkIssuedPerBdv(token)).toUint128(), germ); LibSilo.mintActiveStalk(msg.sender, grownStalk); } LibTokenSilo.addDepositToAccount( msg.sender, token, stem, amount, bdv, LibTokenSilo.Transfer.emitTransferSingle ); } }
// 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 "../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 "./AppStorage.sol"; /** * @author Beanstalk Farms * @title Variation of Oepn Zeppelins reentrant guard to include Silo Update * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts%2Fsecurity%2FReentrancyGuard.sol **/ abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; AppStorage internal s; modifier nonReentrant() { require(s.reentrantStatus != _ENTERED, "ReentrancyGuard: reentrant call"); s.reentrantStatus = _ENTERED; _; s.reentrantStatus = _NOT_ENTERED; } }
// 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; interface IFertilizer { struct Balance { uint128 amount; uint128 lastBpf; } function beanstalkUpdate( address account, uint256[] memory ids, uint128 bpf ) external returns (uint256); function beanstalkMint(address account, uint256 id, uint128 amount, uint128 bpf) external; function balanceOfFertilized(address account, uint256[] memory ids) external view returns (uint256); function balanceOfUnfertilized(address account, uint256[] memory ids) external view returns (uint256); function lastBalanceOf(address account, uint256 id) external view returns (Balance memory); function lastBalanceOfBatch(address[] memory account, uint256[] memory id) external view returns (Balance[] memory); function setURI(string calldata newuri) external; }
// 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 */ library LibConvert { using SafeMath for uint256; using LibConvertData for bytes; using LibWell for address; /** * @notice Takes in bytes object that has convert input data encoded into it for a particular convert for * a specified pool and returns the in and out convert amounts and token addresses and bdv * @param convertData Contains convert input parameters for a specified convert */ function convert(bytes calldata convertData) external returns ( address tokenOut, address tokenIn, uint256 amountOut, uint256 amountIn ) { LibConvertData.ConvertKind kind = convertData.convertKind(); // if (kind == LibConvertData.ConvertKind.BEANS_TO_CURVE_LP) { // (tokenOut, tokenIn, amountOut, amountIn) = LibCurveConvert // .convertBeansToLP(convertData); if (kind == LibConvertData.ConvertKind.CURVE_LP_TO_BEANS) { (tokenOut, tokenIn, amountOut, amountIn) = LibCurveConvert .convertLPToBeans(convertData); } else if (kind == LibConvertData.ConvertKind.UNRIPE_BEANS_TO_UNRIPE_LP) { (tokenOut, tokenIn, amountOut, amountIn) = LibUnripeConvert .convertBeansToLP(convertData); } else if (kind == LibConvertData.ConvertKind.UNRIPE_LP_TO_UNRIPE_BEANS) { (tokenOut, tokenIn, amountOut, amountIn) = LibUnripeConvert .convertLPToBeans(convertData); } else if (kind == LibConvertData.ConvertKind.LAMBDA_LAMBDA) { (tokenOut, tokenIn, amountOut, amountIn) = LibLambdaConvert .convert(convertData); } else if (kind == LibConvertData.ConvertKind.BEANS_TO_WELL_LP) { (tokenOut, tokenIn, amountOut, amountIn) = LibWellConvert .convertBeansToLP(convertData); } else if (kind == LibConvertData.ConvertKind.WELL_LP_TO_BEANS) { (tokenOut, tokenIn, amountOut, amountIn) = LibWellConvert .convertLPToBeans(convertData); } else if (kind == LibConvertData.ConvertKind.UNRIPE_TO_RIPE) { (tokenOut, tokenIn, amountOut, amountIn) = LibChopConvert .convertUnripeToRipe(convertData); } else { revert("Convert: Invalid payload"); } } function getMaxAmountIn(address tokenIn, address tokenOut) internal view returns (uint256) { /// BEAN:3CRV LP -> BEAN if (tokenIn == C.CURVE_BEAN_METAPOOL && tokenOut == C.BEAN) return LibCurveConvert.lpToPeg(C.CURVE_BEAN_METAPOOL); /// BEAN -> BEAN:3CRV LP // NOTE: cannot convert due to bean:3crv dewhitelisting // if (tokenIn == C.BEAN && tokenOut == C.CURVE_BEAN_METAPOOL) // return LibCurveConvert.beansToPeg(C.CURVE_BEAN_METAPOOL); // Lambda -> Lambda if (tokenIn == tokenOut) return type(uint256).max; // Bean -> Well LP Token if (tokenIn == C.BEAN && tokenOut.isWell()) return LibWellConvert.beansToPeg(tokenOut); // Well LP Token -> Bean if (tokenIn.isWell() && tokenOut == C.BEAN) return LibWellConvert.lpToPeg(tokenIn); // urLP Convert if (tokenIn == C.UNRIPE_LP){ // UrBEANETH -> urBEAN if (tokenOut == C.UNRIPE_BEAN) return LibUnripeConvert.lpToPeg(); // UrBEANETH -> BEANETH if (tokenOut == LibBarnRaise.getBarnRaiseWell()) return type(uint256).max; } // urBEAN Convert if (tokenIn == C.UNRIPE_BEAN){ // urBEAN -> urLP if (tokenOut == C.UNRIPE_LP) return LibUnripeConvert.beansToPeg(); // UrBEAN -> BEAN if (tokenOut == C.BEAN) return type(uint256).max; } revert("Convert: Tokens not supported"); } function getAmountOut(address tokenIn, address tokenOut, uint256 amountIn) internal view returns (uint256) { /// BEAN:3CRV LP -> BEAN if (tokenIn == C.CURVE_BEAN_METAPOOL && tokenOut == C.BEAN) return LibCurveConvert.getBeanAmountOut(C.CURVE_BEAN_METAPOOL, amountIn); /// BEAN -> BEAN:3CRV LP // NOTE: cannot convert due to bean:3crv dewhitelisting // if (tokenIn == C.BEAN && tokenOut == C.CURVE_BEAN_METAPOOL) // return LibCurveConvert.getLPAmountOut(C.CURVE_BEAN_METAPOOL, amountIn); /// urLP -> urBEAN if (tokenIn == C.UNRIPE_LP && tokenOut == C.UNRIPE_BEAN) return LibUnripeConvert.getBeanAmountOut(amountIn); /// urBEAN -> urLP if (tokenIn == C.UNRIPE_BEAN && tokenOut == C.UNRIPE_LP) return LibUnripeConvert.getLPAmountOut(amountIn); // Lambda -> Lambda if (tokenIn == tokenOut) return amountIn; // Bean -> Well LP Token if (tokenIn == C.BEAN && tokenOut.isWell()) return LibWellConvert.getLPAmountOut(tokenOut, amountIn); // Well LP Token -> Bean if (tokenIn.isWell() && tokenOut == C.BEAN) return LibWellConvert.getBeanAmountOut(tokenIn, amountIn); // UrBEAN -> Bean if (tokenIn == C.UNRIPE_BEAN && tokenOut == C.BEAN) return LibChopConvert.getConvertedUnderlyingOut(tokenIn, amountIn); // UrBEANETH -> BEANETH if (tokenIn == C.UNRIPE_LP && tokenOut == LibBarnRaise.getBarnRaiseWell()) return LibChopConvert.getConvertedUnderlyingOut(tokenIn, amountIn); 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 } /// @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)); } }
// 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 */ library LibLambdaConvert { using LibConvertData for bytes; function convert(bytes memory convertData) internal pure returns ( address tokenOut, address tokenIn, uint256 amountOut, uint256 amountIn ) { (amountIn, tokenIn) = convertData.lambdaConvert(); tokenOut = tokenIn; amountOut = amountIn; } }
// 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; /* * @author: Malteasy * @title: LibBytes */ library LibBytes { /* * @notice From Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> */ function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) { require(_start + 1 >= _start, "toUint8_overflow"); require(_bytes.length >= _start + 1 , "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } /* * @notice From Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> */ function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) { require(_start + 4 >= _start, "toUint32_overflow"); require(_bytes.length >= _start + 4, "toUint32_outOfBounds"); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } /* * @notice From Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> */ function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) { require(_start + 32 >= _start, "toUint256_overflow"); require(_bytes.length >= _start + 32, "toUint256_outOfBounds"); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } /** * @notice Loads a slice of a calldata bytes array into memory * @param b The calldata bytes array to load from * @param start The start of the slice * @param length The length of the slice */ function sliceToMemory(bytes calldata b, uint256 start, uint256 length) internal pure returns (bytes memory) { bytes memory memBytes = new bytes(length); for(uint256 i = 0; i < length; ++i) { memBytes[i] = b[start + i]; } return memBytes; } function packAddressAndStem(address _address, int96 stem) internal pure returns (uint256) { return uint256(_address) << 96 | uint96(stem); } function unpackAddressAndStem(uint256 data) internal pure returns(address, int96) { return (address(uint160(data >> 96)), int96(int256(data))); } }
// 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); LibUnripe.decrementUnderlying(unripeToken, underlyingAmount); underlyingToken = s.u[unripeToken].underlyingToken; } }
// 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 Sprouts that have been Rinsed or are Rinsable. * Should have 6 decimal precision. * * @dev Solves the below equation for N_{⌈U/i⌉}: * N_{t+1} = N_t - i * R * N_t / (U - i * t) * where: * - N_t is the number of Underlying Tokens at step t * - U is the starting number of Unripe Tokens * - R is the % of Sprouts that are Rinsable or Rinsed * - 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 > 5_000_000) { if (unripeSupply > 10_000_000) { if (recapPercentPaid > 0.1e6) { if (recapPercentPaid > 0.21e6) { if (recapPercentPaid > 0.38e6) { if (recapPercentPaid > 0.45e6) { return 0.000106800755371506e18; // 90,000,000, 0.9 } else { return 0.019890729697455534e18; // 90,000,000, 0.45 } } else if (recapPercentPaid > 0.29e6) { if (recapPercentPaid > 0.33e6) { return 0.038002726385307994e18; // 90,000,000 0.38 } else { return 0.05969915165233464e18; // 90,000,000 0.33 } } else if (recapPercentPaid > 0.25e6) { if (recapPercentPaid > 0.27e6) { return 0.08520038853809475e18; // 90,000,000 0.29 } else { return 0.10160827712172482e18; // 90,000,000 0.27 } } else { if (recapPercentPaid > 0.23e6) { return 0.1210446758987509e18; // 90,000,000 0.25 } else { return 0.14404919400935834e18; // 90,000,000 0.23 } } } else { if (recapPercentPaid > 0.17e6) { if (recapPercentPaid > 0.19e6) { return 0.17125472579906187e18; // 90,000,000, 0.21 } else { return 0.2034031571094802e18; // 90,000,000, 0.19 } } else if (recapPercentPaid > 0.14e6) { if (recapPercentPaid > 0.15e6) { return 0.24136365460186238e18; // 90,000,000 0.17 } else { return 0.2861539540121635e18; // 90,000,000 0.15 } } else if (recapPercentPaid > 0.12e6) { if (recapPercentPaid > 0.13e6) { return 0.3114749615435798e18; // 90,000,000 0.14 } else { return 0.3389651289211062e18; // 90,000,000 0.13 } } else { if (recapPercentPaid > 0.11e6) { return 0.3688051484970447e18; // 90,000,000 0.12 } else { return 0.4011903974987394e18; // 90,000,000 0.11 } } } } else { if (recapPercentPaid > 0.04e6) { if (recapPercentPaid > 0.08e6) { if (recapPercentPaid > 0.09e6) { return 0.4363321054081788e18; // 90,000,000, 0.1 } else { return 0.4744586123058411e18; // 90,000,000, 0.09 } } else if (recapPercentPaid > 0.06e6) { if (recapPercentPaid > 0.07e6) { return 0.5158167251384363e18; // 90,000,000 0.08 } else { return 0.560673179393784e18; // 90,000,000 0.07 } } else if (recapPercentPaid > 0.05e6) { if (recapPercentPaid > 0.055e6) { return 0.6093162142284054e18; // 90,000,000 0.06 } else { return 0.6351540690346162e18; // 90,000,000 0.055 } } else { if (recapPercentPaid > 0.045e6) { return 0.6620572696973799e18; // 90,000,000 0.05 } else { return 0.6900686713435757e18; // 90,000,000 0.045 } } } else { if (recapPercentPaid > 0.03e6) { if (recapPercentPaid > 0.035e6) { return 0.7192328153846157e18; // 90,000,000, 0.04 } else { return 0.7495959945573412e18; // 90,000,000, 0.035 } } else if (recapPercentPaid > 0.02e6) { if (recapPercentPaid > 0.025e6) { return 0.7812063204281795e18; // 90,000,000 0.03 } else { return 0.8141137934523504e18; // 90,000,000 0.025 } } else if (recapPercentPaid > 0.01e6) { if (recapPercentPaid > 0.015e6) { return 0.8483703756831885e18; // 90,000,000 0.02 } else { return 0.8840300662301638e18; // 90,000,000 0.015 } } else { if (recapPercentPaid > 0.005e6) { return 0.921148979567821e18; // 90,000,000 0.01 } else { return 0.9597854268015467e18; // 90,000,000 0.005 } } } } } else { // > 5,000,000 if (recapPercentPaid > 0.1e6) { if (recapPercentPaid > 0.21e6) { if (recapPercentPaid > 0.38e6) { if (recapPercentPaid > 0.45e6) { return 0.000340444522821781e18; // 10,000,000, 0.9 } else { return 0.04023093970853808e18; // 10,000,000, 0.45 } } else if (recapPercentPaid > 0.29e6) { if (recapPercentPaid > 0.33e6) { return 0.06954881077191022e18; // 10,000,000 0.38 } else { return 0.10145116013499655e18; // 10,000,000 0.33 } } else if (recapPercentPaid > 0.25e6) { if (recapPercentPaid > 0.27e6) { return 0.13625887314323348e18; // 10,000,000 0.29 } else { return 0.15757224609763754e18; // 10,000,000 0.27 } } else { if (recapPercentPaid > 0.23e6) { return 0.18197183407669726e18; // 10,000,000 0.25 } else { return 0.20987581330872107e18; // 10,000,000 0.23 } } } else { if (recapPercentPaid > 0.17e6) { if (recapPercentPaid > 0.19e6) { return 0.24175584233885106e18; // 10,000,000, 0.21 } else { return 0.27814356260741413e18; // 10,000,000, 0.19 } } else if (recapPercentPaid > 0.14e6) { if (recapPercentPaid > 0.15e6) { return 0.3196378540296301e18; // 10,000,000 0.17 } else { return 0.36691292973511136e18; // 10,000,000 0.15 } } else if (recapPercentPaid > 0.1e6) { if (recapPercentPaid > 0.13e6) { return 0.3929517529835418e18; // 10,000,000 0.14 } else { return 0.4207273631610372e18; // 10,000,000 0.13 } } else { if (recapPercentPaid > 0.11e6) { return 0.450349413795883e18; // 10,000,000 0.12 } else { return 0.4819341506654745e18; // 10,000,000 0.11 } } } } else { if (recapPercentPaid > 0.04e6) { if (recapPercentPaid > 0.08e6) { if (recapPercentPaid > 0.09e6) { return 0.5156047910307769e18; // 10,000,000, 0.1 } else { return 0.551491923831086e18; // 10,000,000, 0.09 } } else if (recapPercentPaid > 0.06e6) { if (recapPercentPaid > 0.07e6) { return 0.5897339319558434e18; // 10,000,000 0.08 } else { return 0.6304774377677631e18; // 10,000,000 0.07 } } else if (recapPercentPaid > 0.05e6) { if (recapPercentPaid > 0.055e6) { return 0.6738777731119263e18; // 10,000,000 0.06 } else { return 0.6966252960203008e18; // 10,000,000 0.055 } } else { if (recapPercentPaid > 0.045e6) { return 0.7200994751088836e18; // 10,000,000 0.05 } else { return 0.7443224016328813e18; // 10,000,000 0.045 } } } else { if (recapPercentPaid > 0.03e6) { if (recapPercentPaid > 0.035e6) { return 0.7693168090963867e18; // 10,000,000, 0.04 } else { return 0.7951060911805916e18; // 10,000,000, 0.035 } } else if (recapPercentPaid > 0.02e6) { if (recapPercentPaid > 0.025e6) { return 0.8217143201541763e18; // 10,000,000 0.03 } else { return 0.8491662657783823e18; // 10,000,000 0.025 } } else if (recapPercentPaid > 0.01e6) { if (recapPercentPaid > 0.015e6) { return 0.8774874147196358e18; // 10,000,000 0.02 } else { return 0.9067039904828691e18; // 10,000,000 0.015 } } else { if (recapPercentPaid > 0.005e6) { return 0.9368429738790524e18; // 10,000,000 0.01 } else { return 0.9679321240407666e18; // 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.000946395082480844e18; // 3,000,000, 0.9 } else { return 0.06786242725985348e18; // 3,000,000, 0.45 } } else if (recapPercentPaid > 0.29e6) { if (recapPercentPaid > 0.33e6) { return 0.10822315472628707e18; // 3,000,000 0.38 } else { return 0.14899524306327216e18; // 3,000,000 0.33 } } else if (recapPercentPaid > 0.25e6) { if (recapPercentPaid > 0.27e6) { return 0.1910488239684135e18; // 3,000,000 0.29 } else { return 0.215863137234529e18; // 3,000,000 0.27 } } else { if (recapPercentPaid > 0.23e6) { return 0.243564628757033e18; // 3,000,000 0.25 } else { return 0.2744582675491247e18; // 3,000,000 0.23 } } } else { if (recapPercentPaid > 0.17e6) { if (recapPercentPaid > 0.19e6) { return 0.3088786047254358e18; // 3,000,000, 0.21 } else { return 0.3471924328319608e18; // 3,000,000, 0.19 } } else if (recapPercentPaid > 0.14e6) { if (recapPercentPaid > 0.15e6) { return 0.38980166833777796e18; // 3,000,000 0.17 } else { return 0.4371464748698771e18; // 3,000,000 0.15 } } else if (recapPercentPaid > 0.12e6) { if (recapPercentPaid > 0.13e6) { return 0.46274355346663876e18; // 3,000,000 0.14 } else { return 0.4897086460787351e18; // 3,000,000 0.13 } } else { if (recapPercentPaid > 0.11e6) { return 0.518109082463349e18; // 3,000,000 0.12 } else { return 0.5480152684204499e18; // 3,000,000 0.11 } } } } else { if (recapPercentPaid > 0.04e6) { if (recapPercentPaid > 0.08e6) { if (recapPercentPaid > 0.09e6) { return 0.5795008171102514e18; // 3,000,000, 0.1 } else { return 0.6126426856374751e18; // 3,000,000, 0.09 } } else if (recapPercentPaid > 0.06e6) { if (recapPercentPaid > 0.07e6) { return 0.6475213171017626e18; // 3,000,000 0.08 } else { return 0.6842207883207123e18; // 3,000,000 0.07 } } else if (recapPercentPaid > 0.05e6) { if (recapPercentPaid > 0.055e6) { return 0.7228289634394097e18; // 3,000,000 0.06 } else { return 0.742877347280416e18; // 3,000,000 0.055 } } else { if (recapPercentPaid > 0.045e6) { return 0.7634376536479606e18; // 3,000,000 0.05 } else { return 0.784522002909275e18; // 3,000,000 0.045 } } } else { if (recapPercentPaid > 0.03e6) { if (recapPercentPaid > 0.035e6) { return 0.8061427832364296e18; // 3,000,000, 0.04 } else { return 0.8283126561589187e18; // 3,000,000, 0.035 } } else if (recapPercentPaid > 0.02e6) { if (recapPercentPaid > 0.025e6) { return 0.8510445622247672e18; // 3,000,000 0.03 } else { return 0.8743517267721741e18; // 3,000,000 0.025 } } else if (recapPercentPaid > 0.01e6) { if (recapPercentPaid > 0.015e6) { return 0.8982476658137254e18; // 3,000,000 0.02 } else { return 0.9227461920352636e18; // 3,000,000 0.015 } } else { if (recapPercentPaid > 0.005e6) { return 0.9478614209115208e18; // 3,000,000 0.01 } else { return 0.9736077769406731e18; // 3,000,000 0.005 } } } } } else { if (recapPercentPaid > 0.1e6) { if (recapPercentPaid > 0.21e6) { if (recapPercentPaid > 0.38e6) { if (recapPercentPaid > 0.45e6) { return 0.003360632002379016e18; // 1,000,000, 0.9 } else { return 0.12071031956650236e18; // 1,000,000, 0.45 } } else if (recapPercentPaid > 0.29e6) { if (recapPercentPaid > 0.33e6) { return 0.1752990554517151e18; // 1,000,000 0.38 } else { return 0.22598948369141458e18; // 1,000,000 0.33 } } else if (recapPercentPaid > 0.25e6) { if (recapPercentPaid > 0.27e6) { return 0.27509697387157794e18; // 1,000,000 0.29 } else { return 0.3029091410266461e18; // 1,000,000 0.27 } } else { if (recapPercentPaid > 0.23e6) { return 0.33311222196618273e18; // 1,000,000 0.25 } else { return 0.36588364748950297e18; // 1,000,000 0.23 } } } else { if (recapPercentPaid > 0.17e6) { if (recapPercentPaid > 0.19e6) { return 0.40141235983370593e18; // 1,000,000, 0.21 } else { return 0.43989947169522015e18; // 1,000,000, 0.19 } } else if (recapPercentPaid > 0.14e6) { if (recapPercentPaid > 0.15e6) { return 0.4815589587559236e18; // 1,000,000 0.17 } else { return 0.5266183872325827e18; // 1,000,000 0.15 } } else if (recapPercentPaid > 0.12e6) { if (recapPercentPaid > 0.13e6) { return 0.5504980973828455e18; // 1,000,000 0.14 } else { return 0.5753196780298556e18; // 1,000,000 0.13 } } else { if (recapPercentPaid > 0.11e6) { return 0.6011157438454372e18; // 1,000,000 0.12 } else { return 0.6279199091408495e18; // 1,000,000 0.11 } } } } else { if (recapPercentPaid > 0.04e6) { if (recapPercentPaid > 0.08e6) { if (recapPercentPaid > 0.09e6) { return 0.6557668151543954e18; // 1,000,000, 0.1 } else { return 0.6846921580052533e18; // 1,000,000, 0.09 } } else if (recapPercentPaid > 0.06e6) { if (recapPercentPaid > 0.07e6) { return 0.7147327173281093e18; // 1,000,000 0.08 } else { return 0.745926385603471e18; // 1,000,000 0.07 } } else if (recapPercentPaid > 0.05e6) { if (recapPercentPaid > 0.055e6) { return 0.7783121981988174e18; // 1,000,000 0.06 } else { return 0.7949646772335068e18; // 1,000,000 0.055 } } else { if (recapPercentPaid > 0.045e6) { return 0.8119303641360465e18; // 1,000,000 0.05 } else { return 0.8292144735871585e18; // 1,000,000 0.045 } } } else { if (recapPercentPaid > 0.03e6) { if (recapPercentPaid > 0.035e6) { return 0.8468222976009872e18; // 1,000,000, 0.04 } else { return 0.8647592065514869e18; // 1,000,000, 0.035 } } else if (recapPercentPaid > 0.02e6) { if (recapPercentPaid > 0.025e6) { return 0.8830306502110374e18; // 1,000,000 0.03 } else { return 0.9016421588014247e18; // 1,000,000 0.025 } } else if (recapPercentPaid > 0.01e6) { if (recapPercentPaid > 0.015e6) { return 0.9205993440573136e18; // 1,000,000 0.02 } else { return 0.9399079003023474e18; // 1,000,000 0.015 } } else { if (recapPercentPaid > 0.005e6) { return 0.959573605538012e18; // 1,000,000 0.01 } else { return 0.9796023225453983e18; // 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.6.0 <0.8.0; /** * @author Publius * @title LibSafeMath32 is a uint32 variation of Open Zeppelin's Safe Math library. **/ library LibSafeMath32 { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint32 a, uint32 b) internal pure returns (bool, uint32) { uint32 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint32 a, uint32 b) internal pure returns (bool, uint32) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint32 a, uint32 b) internal pure returns (bool, uint32) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint32 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint32 a, uint32 b) internal pure returns (bool, uint32) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint32 a, uint32 b) internal pure returns (bool, uint32) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint32 a, uint32 b) internal pure returns (uint32) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint32 a, uint32 b) internal pure returns (uint32) { if (a == 0) return 0; uint32 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint32 a, uint32 b) internal pure returns (uint32) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint32 a, uint32 b) internal pure returns (uint32) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b > 0, errorMessage); return a % b; } }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library LibSafeMathSigned128 { int128 constant private _INT128_MIN = -2**127; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int128 a, int128 b) internal pure returns (int128) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT128_MIN), "SignedSafeMath: multiplication overflow"); int128 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int128 a, int128 b) internal pure returns (int128) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT128_MIN), "SignedSafeMath: division overflow"); int128 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int128 a, int128 b) internal pure returns (int128) { int128 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int128 a, int128 b) internal pure returns (int128) { int128 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library LibSafeMathSigned96 { int96 constant private _INT96_MIN = -2**95; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int96 a, int96 b) internal pure returns (int96) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT96_MIN), "SignedSafeMath: multiplication overflow"); int96 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int96 a, int96 b) internal pure returns (int96) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT96_MIN), "SignedSafeMath: division overflow"); int96 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int96 a, int96 b) internal pure returns (int96) { int96 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int96 a, int96 b) internal pure returns (int96) { int96 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } }
// 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"; /** * @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); } function _getPenalizedUnderlying( address unripeToken, uint256 amount, uint256 supply ) internal view returns (uint256 redeem) { require(isUnripe(unripeToken), "not vesting"); uint256 sharesBeingRedeemed = getRecapPaidPercentAmount(amount); redeem = _getUnderlying(unripeToken, sharesBeingRedeemed, supply); } /** * @notice Calculates the the amount of Ripe Tokens that would be paid out if * all Unripe Tokens were Chopped at the current Chop Rate. */ function _getTotalPenalizedUnderlying( address unripeToken ) internal view returns (uint256 redeem) { require(isUnripe(unripeToken), "not vesting"); uint256 supply = IERC20(unripeToken).totalSupply(); redeem = _getUnderlying(unripeToken, getRecapPaidPercentAmount(supply), supply); } /** * @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, getRecapPaidPercentAmount(1e6)) .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, getRecapPaidPercentAmount(1e6) ); 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); } /** * @notice Returns the underlying token amount of the unripe token. */ function _getUnderlying( address unripeToken, uint256 amount, uint256 supply ) internal view returns (uint256 redeem) { AppStorage storage s = LibAppStorage.diamondStorage(); redeem = s.u[unripeToken].balanceOfUnderlying.mul(amount).div(supply); } }
/** * 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 {LibAppStorage, Storage, AppStorage, Account} from "../LibAppStorage.sol"; import {LibSafeMath128} from "../LibSafeMath128.sol"; import {LibSafeMath32} from "../LibSafeMath32.sol"; import {LibSafeMathSigned96} from "../LibSafeMathSigned96.sol"; import {LibTokenSilo} from "./LibTokenSilo.sol"; import {LibSilo} from "./LibSilo.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {C} from "../../C.sol"; /** * @title LibGerminate * @author Brean * @notice LibGerminate handles logic associated with germination. * @dev "germinating" values are values that are currently inactive. * germinating values stay germinating until the 1 + the remainder of the current season as passed, * in which case they become active. * * The following are germinating: * - newly issued stalk (from new deposits or mowing) * - roots from newly issued stalk * - new bdv introduced in the silo. */ library LibGerminate { using SafeMath for uint256; using SafeCast for uint256; using LibSafeMath32 for uint32; using LibSafeMath128 for uint128; using LibSafeMathSigned96 for int96; //////////////////////// EVENTS //////////////////////// /** * @notice emitted when the farmers germinating stalk changes. */ event FarmerGerminatingStalkBalanceChanged( address indexed account, int256 deltaGerminatingStalk, Germinate germinationState ); /** * @notice emitted when the total germinating amount/bdv changes. * @param germinationSeason the season the germination occured. * Does not always equal the current season. * @param token the token being updated. * @param deltaAmount the change in the total germinating amount. * @param deltaBdv the change in the total germinating bdv. */ event TotalGerminatingBalanceChanged( uint256 germinationSeason, address indexed token, int256 deltaAmount, int256 deltaBdv ); /** * @notice emitted when the total germinating stalk changes. * @param germinationSeason issuance season of germinating stalk * @param deltaGerminatingStalk the change in the total germinating stalk. * @dev the issuance season may differ from the season that this event was emitted in.. */ event TotalGerminatingStalkChanged(uint256 germinationSeason, int256 deltaGerminatingStalk); /** * @notice emitted at the sunrise function when the total stalk and roots are incremented. * @dev currently, stalk and roots can only increase at the end of `endTotalGermination`, * but is casted in the event to allow for future decreases. */ event TotalStalkChangedFromGermination(int256 deltaStalk, int256 deltaRoots); struct GermStem { int96 germinatingStem; int96 stemTip; } /** * @notice Germinate determines what germination struct to use. * @dev "odd" and "even" refers to the value of the season counter. * "Odd" germinations are used when the season is odd, and vice versa. */ enum Germinate { ODD, EVEN, NOT_GERMINATING } /** * @notice Ends the germination process of system-wide values. * @dev we calculate the unclaimed germinating roots of 2 seasons ago * as the roots of the stalk should be calculated based on the total stalk * when germination finishes, rather than when germination starts. */ function endTotalGermination(uint32 season, address[] memory tokens) external { AppStorage storage s = LibAppStorage.diamondStorage(); // germination can only occur after season 3. if (season < 2) return; uint32 germinationSeason = season.sub(2); // base roots are used if there are no roots in the silo. // root calculation is skipped if no deposits have been made // in the season. uint128 finishedGerminatingStalk = s.unclaimedGerminating[germinationSeason].stalk; uint128 rootsFromGerminatingStalk; if (s.s.roots == 0) { rootsFromGerminatingStalk = finishedGerminatingStalk.mul(uint128(C.getRootsBase())); } else if (s.unclaimedGerminating[germinationSeason].stalk > 0) { rootsFromGerminatingStalk = s.s.roots.mul(finishedGerminatingStalk).div(s.s.stalk).toUint128(); } s.unclaimedGerminating[germinationSeason].roots = rootsFromGerminatingStalk; // increment total stalk and roots based on unclaimed values. s.s.stalk = s.s.stalk.add(finishedGerminatingStalk); s.s.roots = s.s.roots.add(rootsFromGerminatingStalk); // increment total deposited and amounts for each token. Storage.TotalGerminating storage totalGerm; if (getSeasonGerminationState() == Germinate.ODD) { totalGerm = s.oddGerminating; } else { totalGerm = s.evenGerminating; } for (uint i; i < tokens.length; ++i) { // if the token has no deposits, skip. if (totalGerm.deposited[tokens[i]].amount == 0) { continue; } LibTokenSilo.incrementTotalDeposited( tokens[i], totalGerm.deposited[tokens[i]].amount, totalGerm.deposited[tokens[i]].bdv ); // emit events. emit TotalGerminatingBalanceChanged( germinationSeason, tokens[i], -int256(totalGerm.deposited[tokens[i]].amount), -int256(totalGerm.deposited[tokens[i]].bdv) ); // clear deposited values. delete totalGerm.deposited[tokens[i]]; } // emit change in total germinating stalk. // safecast not needed as finishedGerminatingStalk is initially a uint128. emit TotalGerminatingStalkChanged(germinationSeason, -int256(finishedGerminatingStalk)); emit TotalStalkChangedFromGermination(int256(finishedGerminatingStalk), int256(rootsFromGerminatingStalk)); } /** * @notice contains logic for ending germination for stalk and roots. * @param account address of the account to end germination for. * @param lastMowedSeason the last season the account mowed. * * @dev `first` refers to the set of germinating stalk * and roots created in the season closest to the current season. * i.e if a user deposited in season 10 and 11, the `first` stalk * would be season 11. * * the germination process: * - increments the assoicated values (bdv, stalk, roots) * - clears the germination struct for the account. * * @return firstGerminatingRoots the roots from the first germinating stalk. * used in {handleRainAndSops} to properly set the rain roots of a user, * if the user had deposited in the season prior to a rain. */ function endAccountGermination( address account, uint32 lastMowedSeason, uint32 currentSeason ) internal returns (uint128 firstGerminatingRoots) { AppStorage storage s = LibAppStorage.diamondStorage(); bool lastUpdateOdd = isSeasonOdd(lastMowedSeason); (uint128 firstStalk, uint128 secondStalk) = getGerminatingStalk(account, lastUpdateOdd); uint128 totalRootsFromGermination; uint128 germinatingStalk; // check to end germination for first stalk. // if last mowed season is greater or equal than (currentSeason - 1), // then the first stalk is still germinating. if (firstStalk > 0 && lastMowedSeason < currentSeason.sub(1)) { (uint128 roots, Germinate germState) = claimGerminatingRoots( account, lastMowedSeason, firstStalk, lastUpdateOdd ); germinatingStalk = firstStalk; totalRootsFromGermination = roots; firstGerminatingRoots = roots; emit FarmerGerminatingStalkBalanceChanged( account, -int256(germinatingStalk), germState ); } // check to end germination for second stalk. if (secondStalk > 0) { (uint128 roots, Germinate germState) = claimGerminatingRoots( account, lastMowedSeason.sub(1), secondStalk, !lastUpdateOdd ); germinatingStalk = germinatingStalk.add(secondStalk); totalRootsFromGermination = totalRootsFromGermination.add(roots); emit FarmerGerminatingStalkBalanceChanged(account, -int256(germinatingStalk), germState); } // increment users stalk and roots. if (germinatingStalk > 0) { s.a[account].s.stalk = s.a[account].s.stalk.add(germinatingStalk); s.a[account].roots = s.a[account].roots.add(totalRootsFromGermination); // emit event. Active stalk is incremented, germinating stalk is decremented. emit LibSilo.StalkBalanceChanged( account, int256(germinatingStalk), int256(totalRootsFromGermination) ); } } /** * @notice Claims the germinating roots of an account, * as well as clears the germinating stalk and roots. * * @param account address of the account to end germination for. * @param season the season to calculate the germinating roots for. * @param stalk the stalk to calculate the germinating roots for. * @param clearOdd whether to clear the odd or even germinating stalk. */ function claimGerminatingRoots( address account, uint32 season, uint128 stalk, bool clearOdd ) private returns (uint128 roots, Germinate germState) { AppStorage storage s = LibAppStorage.diamondStorage(); roots = calculateGerminatingRoots(season, stalk); if (clearOdd) { delete s.a[account].farmerGerminating.odd; germState = Germinate.ODD; } else { delete s.a[account].farmerGerminating.even; germState = Germinate.EVEN; } // deduct from unclaimed values. s.unclaimedGerminating[season].stalk = s.unclaimedGerminating[season].stalk.sub(stalk); s.unclaimedGerminating[season].roots = s.unclaimedGerminating[season].roots.sub(roots); } /** * @notice calculates the germinating roots for a given stalk and season. * @param season the season to use when calculating the germinating roots. * @param stalk the stalk to calculate the germinating roots for. */ function calculateGerminatingRoots( uint32 season, uint128 stalk ) private view returns (uint128 roots) { AppStorage storage s = LibAppStorage.diamondStorage(); // if the stalk is equal to the remaining unclaimed germinating stalk, // then return the remaining unclaimed germinating roots. if (stalk == s.unclaimedGerminating[season].stalk) { roots = s.unclaimedGerminating[season].roots; } else { // calculate the roots. casted up to uint256 to prevent overflow, // and safecasted down. roots = uint256(stalk).mul(s.unclaimedGerminating[season].roots).div( s.unclaimedGerminating[season].stalk ).toUint128(); } } /** * @notice returns the germinatingStalk of the account, * ordered based on the parity of lastUpdate. * @dev if lastUpdate is odd, then `firstStalk` is the odd stalk. */ function getGerminatingStalk( address account, bool lastUpdateOdd ) internal view returns (uint128 firstStalk, uint128 secondStalk) { AppStorage storage s = LibAppStorage.diamondStorage(); if (lastUpdateOdd) { firstStalk = s.a[account].farmerGerminating.odd; secondStalk = s.a[account].farmerGerminating.even; } else { firstStalk = s.a[account].farmerGerminating.even; secondStalk = s.a[account].farmerGerminating.odd; } } /** * @notice returns the germinating stalk and roots that will finish germinating * upon an interaction with the silo. */ function getFinishedGerminatingStalkAndRoots( address account, uint32 lastMowedSeason, uint32 currentSeason ) internal view returns (uint256 germinatingStalk, uint256 germinatingRoots) { // if user has mowed already, // then there are no germinating stalk and roots to finish. if (lastMowedSeason == currentSeason) { return (0, 0); } (uint128 firstStalk, uint128 secondStalk) = getGerminatingStalk( account, isSeasonOdd(lastMowedSeason) ); // check to end germination for first stalk. // if last mowed season is the greater or equal than (currentSeason - 1), // then the first stalk is still germinating. if (firstStalk > 0 && lastMowedSeason < currentSeason.sub(1)) { germinatingStalk = firstStalk; germinatingRoots = calculateGerminatingRoots(lastMowedSeason, firstStalk); } // check to end germination for second stalk. if (secondStalk > 0) { germinatingStalk = germinatingStalk.add(secondStalk); germinatingRoots = germinatingRoots.add( calculateGerminatingRoots(lastMowedSeason.sub(1), secondStalk) ); } } /** * @notice returns the stalk currently germinating for an account. * Does not include germinating stalk that will finish germinating * upon an interaction with the silo. */ function getCurrentGerminatingStalk( address account, uint32 lastMowedSeason ) internal view returns (uint256 germinatingStalk) { AppStorage storage s = LibAppStorage.diamondStorage(); // if the last mowed season is less than the current season - 1, // then there are no germinating stalk and roots (as all germinating assets have finished). if (lastMowedSeason < s.season.current.sub(1)) { return 0; } else { (uint128 firstStalk, uint128 secondStalk) = getGerminatingStalk( account, isSeasonOdd(lastMowedSeason) ); germinatingStalk = firstStalk.add(secondStalk); } } /** * @notice returns the unclaimed germinating stalk and roots. */ function getUnclaimedGerminatingStalkAndRoots( uint32 season ) internal view returns (Storage.Sr memory unclaimed) { AppStorage storage s = LibAppStorage.diamondStorage(); unclaimed = s.unclaimedGerminating[season]; } /** * @notice returns the total germinating bdv and amount for a token. */ function getTotalGerminatingForToken( address token ) internal view returns (uint256 bdv, uint256 amount) { AppStorage storage s = LibAppStorage.diamondStorage(); return ( s.oddGerminating.deposited[token].bdv.add(s.evenGerminating.deposited[token].bdv), s.oddGerminating.deposited[token].amount.add(s.evenGerminating.deposited[token].amount) ); } /** * @notice determines whether a deposit (token + stem) should be germinating or not. * If germinating, determines whether the deposit should be set to even or odd. * * @dev `getGerminationState` should be used if the stemTip and germinatingStem * have not been calculated yet. Otherwise, use `_getGerminationState` for gas effiecnecy. */ function getGerminationState( address token, int96 stem ) internal view returns (Germinate, int96) { GermStem memory germStem = getGerminatingStem(token); return (_getGerminationState(stem, germStem), germStem.stemTip); } /** * @notice returns the `germinating` stem of a token. * @dev the 'germinating' stem is the stem where deposits that have a stem * equal or higher than this value are germinating. */ function getGerminatingStem(address token) internal view returns (GermStem memory germStem) { germStem.stemTip = LibTokenSilo.stemTipForToken(token); germStem.germinatingStem = _getGerminatingStem(token, germStem.stemTip); } /** * @notice returns the `germinating` stem of a token. * @dev the 'germinating' stem is the stem where deposits that have a stem * equal or higher than this value are germinating. */ function _getGerminatingStem(address token, int96 stemTip) internal view returns (int96 stem) { return __getGerminatingStem(stemTip, getPrevStalkEarnedPerSeason(token)); } /** * @notice Gas efficent version of `_getGerminatingStem`. * * @dev use when the stemTip and germinatingStem have already been calculated. * Assumes the same token is used. * prevStalkEarnedPerSeason is the stalkEarnedPerSeason of the previous season. * since `lastStemTip` + `prevStalkEarnedPerSeason` is the current stemTip, * safeMath is not needed. */ function __getGerminatingStem( int96 stemTip, int96 prevStalkEarnedPerSeason ) internal pure returns (int96 stem) { return stemTip - prevStalkEarnedPerSeason; } /** * @notice returns the stalkEarnedPerSeason of a token of the previous season. * @dev if the milestone season is not the current season, then the stalkEarnedPerSeason * hasn't changed from the previous season. Otherwise, we calculate the prevStalkEarnedPerSeason. */ function getPrevStalkEarnedPerSeason( address token ) private view returns (uint32 prevStalkEarnedPerSeason) { AppStorage storage s = LibAppStorage.diamondStorage(); if (s.ss[token].milestoneSeason < s.season.current) { prevStalkEarnedPerSeason = s.ss[token].stalkEarnedPerSeason; } else { int24 deltaStalkEarnedPerSeason = s.ss[token].deltaStalkEarnedPerSeason; if (deltaStalkEarnedPerSeason >= 0) { prevStalkEarnedPerSeason = s.ss[token].stalkEarnedPerSeason - uint32(deltaStalkEarnedPerSeason); } else { prevStalkEarnedPerSeason = s.ss[token].stalkEarnedPerSeason + uint32(-deltaStalkEarnedPerSeason); } } } /** * @notice internal function for germination stem. * @dev a deposit is germinating if the stem is the stemTip or the germinationStem. * the 'germinationStem` is the stem of the token of the previous season. * * The function must check whether the stem is equal to the germinationStem, * to determine which germination state it is in. */ function _getGerminationState( int96 stem, GermStem memory germData ) internal view returns (Germinate) { if (stem < germData.germinatingStem) { // if the stem of the deposit is lower than the germination stem, // then the deposit is not germinating. return Germinate.NOT_GERMINATING; } else { // return the gemination state based on whether the stem // is equal to the stemTip. // if the stem is equal to the stem tip, it is in the initial stages of germination. // if the stem is not equal to the stemTip, its in the germination process. if (stem == germData.stemTip) { return isCurrentSeasonOdd() ? Germinate.ODD : Germinate.EVEN; } else { return isCurrentSeasonOdd() ? Germinate.EVEN : Germinate.ODD; } } } /** * @notice returns the germination state for the current season. * @dev used in new deposits, as all new deposits are germinating. */ function getSeasonGerminationState() internal view returns (Germinate) { AppStorage storage s = LibAppStorage.diamondStorage(); return getGerminationStateForSeason(s.season.current); } /** * @notice returns the germination state for a given season. */ function getGerminationStateForSeason(uint32 season) internal pure returns (Germinate) { return isSeasonOdd(season) ? Germinate.ODD : Germinate.EVEN; } /** * @notice returns whether the current season is odd. Used for Germination. * @dev even % 2 = 0 (false), odd % 2 = 1 (true) */ function isCurrentSeasonOdd() internal view returns (bool) { AppStorage storage s = LibAppStorage.diamondStorage(); return isSeasonOdd(s.season.current); } /** * @notice returns whether `season` is odd. */ function isSeasonOdd(uint32 season) internal pure returns (bool) { return season.mod(2) == 0 ? false : true; } }
/** * SPDX-License-Identifier: MIT **/ pragma solidity =0.7.6; pragma abicoder v2; import "../LibAppStorage.sol"; import {C} from "../../C.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol"; import {LibBytes} from "../LibBytes.sol"; import {LibTokenSilo} from "./LibTokenSilo.sol"; import {LibSafeMath128} from "../LibSafeMath128.sol"; import {LibSafeMath32} from "../LibSafeMath32.sol"; import {LibSafeMathSigned96} from "../LibSafeMathSigned96.sol"; import {LibGerminate} from "./LibGerminate.sol"; import {LibWhitelistedTokens} from "./LibWhitelistedTokens.sol"; /** * @title LibSilo * @author Publius * @notice Contains functions for minting, burning, and transferring of * Stalk and Roots within the Silo. * * @dev Here, we refer to "minting" as the combination of * increasing the total balance of Stalk/Roots, as well as allocating * them to a particular account. However, in other places throughout Beanstalk * (like during the Sunrise), Beanstalk's total balance of Stalk increases * without allocating to a particular account. One example is {Sun-rewardToSilo} * which increases `s.s.stalk` but does not allocate it to any account. The * allocation occurs during `{SiloFacet-plant}`. Does this change how we should * call "minting"? * * In the ERC20 context, "minting" increases the supply of a token and allocates * the new tokens to an account in one action. I've adjusted the comments below * to use "mint" in the same sense. */ library LibSilo { using SafeMath for uint256; using LibSafeMath128 for uint128; using LibSafeMathSigned96 for int96; using LibSafeMath32 for uint32; using SafeCast for uint256; //////////////////////// ENUM //////////////////////// /** * @dev when a user removes multiple deposits, the * {TransferBatch} event is emitted. However, in the * case of an enroot, the event is omitted (as the * depositID does not change). This enum is * used to determine if the event should be emitted. */ enum ERC1155Event { EMIT_BATCH_EVENT, NO_EMIT_BATCH_EVENT } uint128 internal constant PRECISION = 1e6; //////////////////////// EVENTS //////////////////////// /** * @notice Emitted when `account` gains or loses Stalk. * @param account The account that gained or lost Stalk. * @param delta The change in Stalk. * @param deltaRoots The change in Roots. * * @dev Should be emitted anytime a Deposit is added, removed or transferred * AND anytime an account Mows Grown Stalk. * * BIP-24 included a one-time re-emission of {StalkBalanceChanged} for * accounts that had executed a Deposit transfer between the Replant and * BIP-24 execution. For more, see: * * [BIP-24](https://bean.money/bip-24) * [Event-Emission](https://github.com/BeanstalkFarms/BIP-24-Event-Emission) */ event StalkBalanceChanged(address indexed account, int256 delta, int256 deltaRoots); /** * @notice Emitted when a deposit is removed from the silo. * * @param account The account assoicated with the removed deposit. * @param token The token address of the removed deposit. * @param stem The stem of the removed deposit. * @param amount The amount of "token" removed from an deposit. * @param bdv The instanteous bdv removed from the deposit. */ event RemoveDeposit( address indexed account, address indexed token, int96 stem, uint256 amount, uint256 bdv ); /** * @notice Emitted when multiple deposits are removed from the silo. * * @param account The account assoicated with the removed deposit. * @param token The token address of the removed deposit. * @param stems A list of stems of the removed deposits. * @param amounts A list of amounts removed from the deposits. * @param amount the total summation of the amount removed. * @param bdvs A list of bdvs removed from the deposits. */ event RemoveDeposits( address indexed account, address indexed token, int96[] stems, uint256[] amounts, uint256 amount, uint256[] bdvs ); /** * AssetsRemoved contains the assets removed * during a withdraw or convert. * * @dev seperated into 3 catagories: * active: non-germinating assets. * odd: odd germinating assets. * even: even germinating assets. * grownStalk from germinating depoists are seperated * as that stalk is not germinating. */ struct AssetsRemoved { Removed active; Removed odd; Removed even; uint256 grownStalkFromGermDeposits; } struct Removed { uint256 tokens; uint256 stalk; uint256 bdv; } /** * @notice Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); //////////////////////// MINT //////////////////////// /** * @dev Mints Stalk and Roots to `account`. * * `roots` are an underlying accounting variable that is used to track * how many earned beans a user has. * * When a farmer's state is updated, the ratio should hold: * * Total Roots User Roots * ------------- = ------------ * Total Stalk User Stalk * * @param account the address to mint Stalk and Roots to * @param stalk the amount of stalk to mint * * @dev Stalk that is not germinating are `active`, meaning that they * are eligible for bean mints. To mint germinating stalk, use * `mintGerminatingStalk`. */ function mintActiveStalk(address account, uint256 stalk) internal { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 roots; if (s.s.roots == 0) { roots = uint256(stalk.mul(C.getRootsBase())); } else { // germinating assets should be considered // when calculating roots roots = s.s.roots.mul(stalk).div(s.s.stalk); } // increment user and total stalk; s.s.stalk = s.s.stalk.add(stalk); s.a[account].s.stalk = s.a[account].s.stalk.add(stalk); // increment user and total roots s.s.roots = s.s.roots.add(roots); s.a[account].roots = s.a[account].roots.add(roots); emit StalkBalanceChanged(account, int256(stalk), int256(roots)); } /** * @notice mintGerminatingStalk contains logic for minting stalk that is germinating. * @dev `germinating stalk` are newly issued stalk that are not eligible for bean mints, * until 2 `gm` calls have passed, at which point they are considered `grown stalk`. * * Since germinating stalk are not elgible for bean mints, when calculating the roots of these * stalk, it should use the stalk and roots of the system once the stalk is fully germinated, * rather than at the time of minting. */ function mintGerminatingStalk( address account, uint128 stalk, LibGerminate.Germinate germ ) internal { AppStorage storage s = LibAppStorage.diamondStorage(); if (germ == LibGerminate.Germinate.ODD) { s.a[account].farmerGerminating.odd = s.a[account].farmerGerminating.odd.add(stalk); } else { s.a[account].farmerGerminating.even = s.a[account].farmerGerminating.even.add(stalk); } // germinating stalk are either newly germinating, or partially germinated. // Thus they can only be incremented in the latest or previous season. uint32 germinationSeason = s.season.current; if (LibGerminate.getSeasonGerminationState() == germ) { s.unclaimedGerminating[germinationSeason].stalk = s.unclaimedGerminating[germinationSeason].stalk.add(stalk); } else { germinationSeason = germinationSeason.sub(1); s.unclaimedGerminating[germinationSeason].stalk = s.unclaimedGerminating[germinationSeason].stalk .add(stalk); } // emit events. emit LibGerminate.FarmerGerminatingStalkBalanceChanged(account, stalk, germ); emit LibGerminate.TotalGerminatingStalkChanged(germinationSeason, stalk); } //////////////////////// BURN //////////////////////// /** * @notice Burns stalk and roots from an account. */ function burnActiveStalk(address account, uint256 stalk) internal returns (uint256 roots) { AppStorage storage s = LibAppStorage.diamondStorage(); if (stalk == 0) return 0; // Calculate the amount of Roots for the given amount of Stalk. roots = s.s.roots.mul(stalk).div(s.s.stalk); if (roots > s.a[account].roots) roots = s.a[account].roots; // Decrease supply of Stalk; Remove Stalk from the balance of `account` s.s.stalk = s.s.stalk.sub(stalk); s.a[account].s.stalk = s.a[account].s.stalk.sub(stalk); // Decrease supply of Roots; Remove Roots from the balance of `account` s.s.roots = s.s.roots.sub(roots); s.a[account].roots = s.a[account].roots.sub(roots); // If it is Raining and the account now has less roots than the // account's current rain roots, set the account's rain roots // to the account's current roots and subtract the difference // from Beanstalk's total rain roots. if (s.a[account].sop.roots > s.a[account].roots) { uint256 deltaRoots = s.a[account].sop.roots.sub(s.a[account].roots); s.a[account].sop.roots = s.a[account].roots; s.r.roots = s.r.roots.sub(deltaRoots); } // emit event. emit StalkBalanceChanged(account, -int256(stalk), -int256(roots)); } /** * @notice Burns germinating stalk. * @dev Germinating stalk does not have any roots assoicated with it. */ function burnGerminatingStalk( address account, uint128 stalk, LibGerminate.Germinate germ ) external { AppStorage storage s = LibAppStorage.diamondStorage(); if (germ == LibGerminate.Germinate.ODD) { s.a[account].farmerGerminating.odd = s.a[account].farmerGerminating.odd.sub(stalk); } else { s.a[account].farmerGerminating.even = s.a[account].farmerGerminating.even.sub(stalk); } // germinating stalk are either newly germinating, or partially germinated. // Thus they can only be decremented in the latest or previous season. uint32 germinationSeason = s.season.current; if (LibGerminate.getSeasonGerminationState() == germ) { s.unclaimedGerminating[germinationSeason].stalk = s.unclaimedGerminating[germinationSeason].stalk.sub(stalk); } else { germinationSeason = germinationSeason.sub(1); s.unclaimedGerminating[germinationSeason].stalk = s.unclaimedGerminating[germinationSeason].stalk .sub(stalk); } // emit events. emit LibGerminate.FarmerGerminatingStalkBalanceChanged(account, -int256(stalk), germ); emit LibGerminate.TotalGerminatingStalkChanged(germinationSeason, -int256(stalk)); } //////////////////////// TRANSFER //////////////////////// /** * @notice Decrements the Stalk and Roots of `sender` and increments the Stalk * and Roots of `recipient` by the same amount. * */ function transferStalk(address sender, address recipient, uint256 stalk) internal { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 roots; roots = stalk == s.a[sender].s.stalk ? s.a[sender].roots : s.s.roots.sub(1).mul(stalk).div(s.s.stalk).add(1); // Subtract Stalk and Roots from the 'sender' balance. s.a[sender].s.stalk = s.a[sender].s.stalk.sub(stalk); s.a[sender].roots = s.a[sender].roots.sub(roots); emit StalkBalanceChanged(sender, -int256(stalk), -int256(roots)); // Rain roots cannot be transferred, burn them if (s.a[sender].sop.roots > s.a[sender].roots) { uint256 deltaRoots = s.a[sender].sop.roots.sub(s.a[sender].roots); s.a[sender].sop.roots = s.a[sender].roots; s.r.roots = s.r.roots.sub(deltaRoots); } // Add Stalk and Roots to the 'recipient' balance. s.a[recipient].s.stalk = s.a[recipient].s.stalk.add(stalk); s.a[recipient].roots = s.a[recipient].roots.add(roots); emit StalkBalanceChanged(recipient, int256(stalk), int256(roots)); } /** * @notice germinating counterpart of `transferStalk`. * @dev assumes stalk is germinating. */ function transferGerminatingStalk( address sender, address recipient, uint256 stalk, LibGerminate.Germinate germState ) internal { AppStorage storage s = LibAppStorage.diamondStorage(); // Subtract Germinating Stalk from the 'sender' balance, // and Add to the 'recipient' balance. if (germState == LibGerminate.Germinate.ODD) { s.a[sender].farmerGerminating.odd = s.a[sender].farmerGerminating.odd.sub(stalk.toUint128()); s.a[recipient].farmerGerminating.odd = s.a[recipient].farmerGerminating.odd.add(stalk.toUint128()); } else { s.a[sender].farmerGerminating.even = s.a[sender].farmerGerminating.even.sub(stalk.toUint128()); s.a[recipient].farmerGerminating.even = s.a[recipient].farmerGerminating.even.add(stalk.toUint128()); } // emit events. emit LibGerminate.FarmerGerminatingStalkBalanceChanged(sender, -int256(stalk), germState); emit LibGerminate.FarmerGerminatingStalkBalanceChanged(recipient, int256(stalk), germState); } /** * @notice transfers both stalk and Germinating Stalk. * @dev used in {TokenSilo._transferDeposits} */ function transferStalkAndGerminatingStalk( address sender, address recipient, address token, AssetsRemoved memory ar ) external { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 stalkPerBDV = s.ss[token].stalkIssuedPerBdv; if (ar.odd.bdv > 0) { uint256 initialStalk = ar.odd.bdv.mul(stalkPerBDV); if (token == C.BEAN) { // check whether the Germinating Stalk transferred exceeds the farmers // Germinating Stalk. If so, the difference is considered from Earned // Beans. Deduct the odd BDV and increment the activeBDV by the difference. (uint256 senderGerminatingStalk, uint256 earnedBeansStalk) = checkForEarnedBeans( sender, initialStalk, LibGerminate.Germinate.ODD ); if (earnedBeansStalk > 0) { // increment the active stalk by the earned beans active stalk. // decrement the germinatingStalk stalk by the earned beans active stalk. ar.active.stalk = ar.active.stalk.add(earnedBeansStalk); initialStalk = senderGerminatingStalk; } } // the inital Stalk issued for a Deposit is the // only Stalk that can Germinate (i.e, Grown Stalk does not Germinate). transferGerminatingStalk( sender, recipient, initialStalk, LibGerminate.Germinate.ODD ); } if (ar.even.bdv > 0) { uint256 initialStalk = ar.even.bdv.mul(stalkPerBDV); if (token == C.BEAN) { // check whether the Germinating Stalk transferred exceeds the farmers // Germinating Stalk. If so, the difference is considered from Earned // Beans. Deduct the even BDV and increment the active BDV by the difference. (uint256 senderGerminatingStalk, uint256 earnedBeansStalk) = checkForEarnedBeans( sender, initialStalk, LibGerminate.Germinate.EVEN ); if (earnedBeansStalk > 0) { // increment the active stalk by the earned beans active stalk. // decrement the germinatingStalk stalk by the earned beans active stalk. ar.active.stalk = ar.active.stalk.add(earnedBeansStalk); initialStalk = senderGerminatingStalk; } } // the inital Stalk issued for a Deposit is the // only Stalk that can Germinate (i.e, Grown Stalk does not Germinate). transferGerminatingStalk( sender, recipient, initialStalk, LibGerminate.Germinate.EVEN ); } // a Germinating Deposit may have Grown Stalk (which is not Germinating), // but the base Stalk is still Germinating. ar.active.stalk = ar.active.stalk // Grown Stalk from non-Germinating Deposits, and base stalk from Earned Bean Deposits. .add(ar.active.bdv.mul(stalkPerBDV)) // base stalk from non-germinating deposits. .add(ar.even.stalk) // grown stalk from Even Germinating Deposits. .add(ar.odd.stalk); // grown stalk from Odd Germinating Deposits. if (ar.active.stalk > 0) { transferStalk(sender, recipient, ar.active.stalk); } } /** * @dev Claims the Grown Stalk for `account` and applies it to their Stalk * balance. Also handles Season of Plenty related rain. * * This is why `_mow()` must be called before any actions that change Seeds, * including: * - {SiloFacet-deposit} * - {SiloFacet-withdrawDeposit} * - {SiloFacet-withdrawDeposits} * - {_plant} * - {SiloFacet-transferDeposit(s)} */ function _mow(address account, address token) internal { AppStorage storage s = LibAppStorage.diamondStorage(); // if the user has not migrated from siloV2, revert. (bool needsMigration, uint32 lastUpdate) = migrationNeeded(account); require(!needsMigration, "Silo: Migration needed"); // if the user hasn't updated prior to the seedGauge/siloV3.1 update, // perform a one time `lastStem` scale. if ( (lastUpdate < s.season.stemScaleSeason && lastUpdate > 0) || (lastUpdate == s.season.stemScaleSeason && checkStemEdgeCase(account)) ) { migrateStems(account); } uint32 currentSeason = s.season.current; // End account germination. uint128 firstGerminatingRoots; if (lastUpdate < currentSeason) { firstGerminatingRoots = LibGerminate.endAccountGermination(account, lastUpdate, currentSeason); } // sop data only needs to be updated once per season, // if it started raining and it's still raining, or there was a sop if (s.season.rainStart > s.season.stemStartSeason) { if ((lastUpdate <= s.season.rainStart || s.a[account].lastRain > 0) && lastUpdate <= currentSeason) { // Increments `plenty` for `account` if a Flood has occured. // Saves Rain Roots for `account` if it is Raining. handleRainAndSops(account, lastUpdate, firstGerminatingRoots); } } // Calculate the amount of Grown Stalk claimable by `account`. // Increase the account's balance of Stalk and Roots. __mow(account, token); // update lastUpdate for sop and germination calculations. s.a[account].lastUpdate = currentSeason; } /** * @dev Updates the mowStatus for the given account and token, * and mints Grown Stalk for the given account and token. */ function __mow( address account, address token ) private { AppStorage storage s = LibAppStorage.diamondStorage(); int96 _stemTip = LibTokenSilo.stemTipForToken(token); int96 _lastStem = s.a[account].mowStatuses[token].lastStem; uint128 _bdv = s.a[account].mowStatuses[token].bdv; // if: // 1: account has no bdv (new token deposit) // 2: the lastStem is the same as the stemTip (implying that a user has mowed), // then skip calculations to save gas. if (_bdv > 0) { if (_lastStem == _stemTip) { return; } // grown stalk does not germinate and is immediately included for bean mints. mintActiveStalk(account, _balanceOfGrownStalk(_lastStem, _stemTip, _bdv)); } // If this `account` has no BDV, skip to save gas. Update lastStem. // (happen on initial deposit, since mow is called before any deposit) s.a[account].mowStatuses[token].lastStem = _stemTip; return; } /** * @notice returns the last season an account interacted with the silo. */ function _lastUpdate(address account) internal view returns (uint32) { AppStorage storage s = LibAppStorage.diamondStorage(); return s.a[account].lastUpdate; } /** * @dev internal logic to handle when beanstalk is raining. */ function handleRainAndSops(address account, uint32 lastUpdate, uint128 firstGerminatingRoots) private { AppStorage storage s = LibAppStorage.diamondStorage(); // If a Sop has occured since last update, calculate rewards and set last Sop. if (s.season.lastSopSeason > lastUpdate) { s.a[account].sop.plenty = balanceOfPlenty(account); s.a[account].lastSop = s.season.lastSop; } // If no roots, reset Sop counters variables if (s.a[account].roots == 0) { s.a[account].lastSop = s.season.rainStart; s.a[account].lastRain = 0; return; } if (s.season.raining) { // If rain started after update, set account variables to track rain. if (s.season.rainStart > lastUpdate) { s.a[account].lastRain = s.season.rainStart; s.a[account].sop.roots = s.a[account].roots; if (s.season.rainStart - 1 == lastUpdate) { if (firstGerminatingRoots > 0) { // if the account had just finished germinating roots this season (i.e, // deposited in the previous season before raining, and mowed during a sop), // Beanstalk will not allocate plenty to this deposit, and thus the roots // needs to be deducted from the sop roots. s.a[account].sop.roots = s.a[account].sop.roots.sub(firstGerminatingRoots); } } // s.a[account].roots includes newly finished germinating roots from a fresh deposit // @ season before rainStart } // If there has been a Sop since rain started, // save plentyPerRoot in case another SOP happens during rain. if (s.season.lastSop == s.season.rainStart) { s.a[account].sop.plentyPerRoot = s.sops[s.season.lastSop]; } } else if (s.a[account].lastRain > 0) { // Reset Last Rain if not raining. s.a[account].lastRain = 0; } } /** * @dev returns the balance of amount of grown stalk based on stems. * @param lastStem the stem assoicated with the last mow * @param latestStem the current stem for a given token * @param bdv the bdv used to calculate grown stalk */ function _balanceOfGrownStalk( int96 lastStem, int96 latestStem, uint128 bdv ) internal pure returns (uint256) { return stalkReward(lastStem, latestStem, bdv); } /** * @dev returns the amount of `plenty` an account has. */ function balanceOfPlenty(address account) internal view returns (uint256 plenty) { AppStorage storage s = LibAppStorage.diamondStorage(); Account.State storage a = s.a[account]; plenty = a.sop.plenty; uint256 previousPPR; // If lastRain > 0, then check if SOP occured during the rain period. if (s.a[account].lastRain > 0) { // if the last processed SOP = the lastRain processed season, // then we use the stored roots to get the delta. if (a.lastSop == a.lastRain) previousPPR = a.sop.plentyPerRoot; else previousPPR = s.sops[a.lastSop]; uint256 lastRainPPR = s.sops[s.a[account].lastRain]; // If there has been a SOP duing the rain sesssion since last update, process SOP. if (lastRainPPR > previousPPR) { uint256 plentyPerRoot = lastRainPPR - previousPPR; previousPPR = lastRainPPR; plenty = plenty.add(plentyPerRoot.mul(s.a[account].sop.roots).div(C.SOP_PRECISION)); } } else { // If it was not raining, just use the PPR at previous SOP. previousPPR = s.sops[s.a[account].lastSop]; } // Handle and SOPs that started + ended before after last Silo update. if (s.season.lastSop > _lastUpdate(account)) { uint256 plentyPerRoot = s.sops[s.season.lastSop].sub(previousPPR); plenty = plenty.add(plentyPerRoot.mul(s.a[account].roots).div(C.SOP_PRECISION)); } } //////////////////////// REMOVE //////////////////////// /** * @dev Removes from a single Deposit, emits the RemoveDeposit event, * and returns the Stalk/BDV that were removed. * * Used in: * - {TokenSilo:_withdrawDeposit} * - {TokenSilo:_transferDeposit} */ function _removeDepositFromAccount( address account, address token, int96 stem, uint256 amount, LibTokenSilo.Transfer transferType ) internal returns ( uint256 initialStalkRemoved, uint256 grownStalkRemoved, uint256 bdvRemoved, LibGerminate.Germinate germ ) { AppStorage storage s = LibAppStorage.diamondStorage(); int96 stemTip; (germ, stemTip) = LibGerminate.getGerminationState(token, stem); bdvRemoved = LibTokenSilo.removeDepositFromAccount(account, token, stem, amount); // the initial and grown stalk are seperated as there are instances // where the initial stalk issued for a deposit is germinating. Grown stalk never germinates, // and thus is not included in the germinating stalk. initialStalkRemoved = bdvRemoved.mul(s.ss[token].stalkIssuedPerBdv); grownStalkRemoved = stalkReward(stem, stemTip, bdvRemoved.toUint128()); /** * {_removeDepositFromAccount} is used for both withdrawing and transferring deposits. * In the case of a withdraw, only the {TransferSingle} Event needs to be emitted. * In the case of a transfer, a different {TransferSingle}/{TransferBatch} * Event is emitted in {TokenSilo._transferDeposit(s)}, * and thus, this event is ommited. */ if (transferType == LibTokenSilo.Transfer.emitTransferSingle) { // "removing" a deposit is equivalent to "burning" an ERC1155 token. emit LibTokenSilo.TransferSingle( msg.sender, // operator account, // from address(0), // to LibBytes.packAddressAndStem(token, stem), // depositid amount // token amount ); } emit RemoveDeposit(account, token, stem, amount, bdvRemoved); } /** * @dev Removes from multiple Deposits, emits the RemoveDeposits * event, and returns the Stalk/BDV that were removed. * * Used in: * - {TokenSilo:_withdrawDeposits} * - {SiloFacet:enrootDeposits} * * @notice with the addition of germination, AssetsRemoved * keeps track of the germinating data. */ function _removeDepositsFromAccount( address account, address token, int96[] calldata stems, uint256[] calldata amounts, ERC1155Event emission ) external returns (AssetsRemoved memory ar) { AppStorage storage s = LibAppStorage.diamondStorage(); uint256[] memory bdvsRemoved = new uint256[](stems.length); uint256[] memory removedDepositIDs = new uint256[](stems.length); LibGerminate.GermStem memory germStem = LibGerminate.getGerminatingStem(token); for (uint256 i; i < stems.length; ++i) { LibGerminate.Germinate germState = LibGerminate._getGerminationState( stems[i], germStem ); uint256 crateBdv = LibTokenSilo.removeDepositFromAccount( account, token, stems[i], amounts[i] ); bdvsRemoved[i] = crateBdv; removedDepositIDs[i] = LibBytes.packAddressAndStem(token, stems[i]); uint256 crateStalk = stalkReward(stems[i], germStem.stemTip, crateBdv.toUint128()); // if the deposit is germinating, decrement germinating values, // otherwise increment deposited values. if (germState == LibGerminate.Germinate.NOT_GERMINATING) { ar.active.bdv = ar.active.bdv.add(crateBdv); ar.active.stalk = ar.active.stalk.add(crateStalk); ar.active.tokens = ar.active.tokens.add(amounts[i]); } else { if (germState == LibGerminate.Germinate.ODD) { ar.odd.bdv = ar.odd.bdv.add(crateBdv); ar.odd.tokens = ar.odd.tokens.add(amounts[i]); } else { ar.even.bdv = ar.even.bdv.add(crateBdv); ar.even.tokens = ar.even.tokens.add(amounts[i]); } // grown stalk from germinating deposits do not germinate, // and thus must be added to the grown stalk. ar.grownStalkFromGermDeposits = ar.grownStalkFromGermDeposits.add( crateStalk ); } } // add initial stalk deposit to all stalk removed. { uint256 stalkIssuedPerBdv = s.ss[token].stalkIssuedPerBdv; if (ar.active.tokens > 0) { ar.active.stalk = ar.active.stalk.add(ar.active.bdv.mul(stalkIssuedPerBdv)); } if (ar.odd.tokens > 0) { ar.odd.stalk = ar.odd.bdv.mul(stalkIssuedPerBdv); } if (ar.even.tokens > 0) { ar.even.stalk = ar.even.bdv.mul(stalkIssuedPerBdv); } } // "removing" deposits is equivalent to "burning" a batch of ERC1155 tokens. if (emission == ERC1155Event.EMIT_BATCH_EVENT) { emit TransferBatch(msg.sender, account, address(0), removedDepositIDs, amounts); } emit RemoveDeposits( account, token, stems, amounts, ar.active.tokens.add(ar.odd.tokens).add(ar.even.tokens), bdvsRemoved ); } //////////////////////// UTILITIES //////////////////////// /** * @notice Calculates the Stalk reward based on the start and end * stems, and the amount of BDV deposited. Stems represent the * amount of grown stalk per BDV, so the difference between the * start index and end index (stem) multiplied by the amount of * bdv deposited will give the amount of stalk earned. * formula: stalk = bdv * (ΔstalkPerBdv) * * @dev endStem must be larger than startStem. * */ function stalkReward( int96 startStem, int96 endStem, uint128 bdv ) internal pure returns (uint256) { uint128 reward = uint128(endStem.sub(startStem)).mul(bdv).div(PRECISION); return reward; } /** * @dev check whether the account needs to be migrated. */ function migrationNeeded(address account) internal view returns (bool needsMigration, uint32 lastUpdate) { AppStorage storage s = LibAppStorage.diamondStorage(); lastUpdate = s.a[account].lastUpdate; needsMigration = lastUpdate > 0 && lastUpdate < s.season.stemStartSeason; } /** * @dev Internal function to compute `account` balance of Earned Beans. * * The number of Earned Beans is equal to the difference between: * - the "expected" Stalk balance, determined from the account balance of * Roots. * - the "account" Stalk balance, stored in account storage. * divided by the number of Stalk per Bean. * The earned beans from the latest season */ function _balanceOfEarnedBeans( uint256 accountStalk, uint256 accountRoots ) internal view returns (uint256 beans) { AppStorage storage s = LibAppStorage.diamondStorage(); // There will be no Roots before the first Deposit is made. if (s.s.roots == 0) return 0; uint256 stalk = s.s.stalk.mul(accountRoots).div(s.s.roots); // Beanstalk rounds down when minting Roots. Thus, it is possible that // balanceOfRoots / totalRoots * totalStalk < s.a[account].s.stalk. // As `account` Earned Balance balance should never be negative, // Beanstalk returns 0 instead. if (stalk <= accountStalk) return 0; // Calculate Earned Stalk and convert to Earned Beans. beans = (stalk - accountStalk).div(C.STALK_PER_BEAN); // Note: SafeMath is redundant here. if (beans > s.earnedBeans) return s.earnedBeans; return beans; } /** * @notice performs a one time update for the * users lastStem for all silo Tokens. * @dev Due to siloV3.1 update. */ function migrateStems(address account) internal { AppStorage storage s = LibAppStorage.diamondStorage(); address[] memory siloTokens = LibWhitelistedTokens.getSiloTokens(); for(uint i; i < siloTokens.length; i++) { // scale lastStem by 1e6, if the user has a lastStem. if (s.a[account].mowStatuses[siloTokens[i]].lastStem > 0) { s.a[account].mowStatuses[siloTokens[i]].lastStem = s.a[account].mowStatuses[siloTokens[i]].lastStem.mul(int96(PRECISION)); } } } /** * @dev An edge case can occur with the siloV3.1 update, where * A user updates their silo in the same season as the seedGauge update, * but prior to the seedGauge BIP execution (i.e the farmer mowed at the start of * the season, and the BIP was excuted mid-way through the season). * This function checks for that edge case and returns a boolean. */ function checkStemEdgeCase(address account) internal view returns (bool) { AppStorage storage s = LibAppStorage.diamondStorage(); address[] memory siloTokens = LibWhitelistedTokens.getSiloTokens(); // for each silo token, divide the stemTip of the token with the users last stem. // if the answer is 1e6 or greater, the user has not updated. for(uint i; i < siloTokens.length; i++) { int96 lastStem = s.a[account].mowStatuses[siloTokens[i]].lastStem; if (lastStem > 0) { if (LibTokenSilo.stemTipForToken(siloTokens[i]).div(lastStem) >= int96(PRECISION)) { return true; } } } return false; } /** * @notice Returns the amount of Germinating Stalk * for a given Germinate enum. * @dev When a Farmer attempts to withdraw Beans from a Deposit that has a Germinating Stem, * `checkForEarnedBeans` is called to determine how many of the Beans were Planted vs Deposited. * If a Farmer withdraws a Germinating Deposit with Earned Beans, only subtract the Germinating Beans * from the Germinating Balances * @return germinatingStalk stalk that is germinating for a given Germinate enum. * @return earnedBeanStalk the earned bean portion of stalk for a given Germinate enum. */ function checkForEarnedBeans( address account, uint256 stalk, LibGerminate.Germinate germ ) internal view returns (uint256 germinatingStalk, uint256 earnedBeanStalk) { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 farmerGerminatingStalk; if (germ == LibGerminate.Germinate.ODD) { farmerGerminatingStalk = s.a[account].farmerGerminating.odd; } else { farmerGerminatingStalk = s.a[account].farmerGerminating.even; } if (stalk > farmerGerminatingStalk) { return (farmerGerminatingStalk, stalk.sub(farmerGerminatingStalk)); } else { return (stalk, 0); } } }
/** * SPDX-License-Identifier: MIT **/ pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol"; import {LibAppStorage, Storage, AppStorage, Account} from "../LibAppStorage.sol"; import {C} from "../../C.sol"; import {LibSafeMath32} from "contracts/libraries/LibSafeMath32.sol"; import {LibSafeMath128} from "contracts/libraries/LibSafeMath128.sol"; import {LibSafeMathSigned128} from "contracts/libraries/LibSafeMathSigned128.sol"; import {LibSafeMathSigned96} from "contracts/libraries/LibSafeMathSigned96.sol"; import {LibBytes} from "contracts/libraries/LibBytes.sol"; import {LibGerminate} from "contracts/libraries/Silo/LibGerminate.sol"; import {LibWhitelistedTokens} from "contracts/libraries/Silo/LibWhitelistedTokens.sol"; /** * @title LibTokenSilo * @author Publius, Pizzaman1337 * @notice Contains functions for depositing, withdrawing and claiming * whitelisted Silo tokens. * * For functionality related to Stalk, and Roots, see {LibSilo}. */ library LibTokenSilo { using SafeMath for uint256; using LibSafeMath128 for uint128; using LibSafeMath32 for uint32; using LibSafeMathSigned128 for int128; using SafeCast for int128; using SafeCast for uint256; using LibSafeMathSigned96 for int96; uint256 constant PRECISION = 1e6; // increased precision from to silo v3.1. //////////////////////// ENUM //////////////////////// /** * @dev when a user deposits or withdraws a deposit, the * {TrasferSingle} event is emitted. However, in the case * of a transfer, this emission is ommited. This enum is * used to determine if the event should be emitted. */ enum Transfer { emitTransferSingle, noEmitTransferSingle } //////////////////////// EVENTS //////////////////////// /** * @dev IMPORTANT: copy of {TokenSilo-AddDeposit}, check there for details. */ event AddDeposit( address indexed account, address indexed token, int96 stem, uint256 amount, uint256 bdv ); /** * @dev IMPORTANT: copy of {TokenSilo-RemoveDeposit}, check there for details. */ event RemoveDeposit( address indexed account, address indexed token, int96 stem, uint256 amount, uint256 bdv ); // added as the ERC1155 deposit upgrade event TransferSingle( address indexed operator, address indexed sender, address indexed recipient, uint256 depositId, uint256 amount ); //////////////////////// ACCOUNTING: TOTALS GERMINATING //////////////////////// /** * @notice Increment the total amount and bdv of `token` germinating in the Silo. * @dev when an asset is `deposited` in the silo, it is not immediately eliable for * bean mints. It must `germinate` (stay deposited the silo) for a certain * amount of seasons (the remainer of the current season + 1). This function * increments the total amount and bdv germinating in the silo. The {sunrise} * function ends the germination process for even or odd germinating deposits. * * This protects beanstalk from flashloan attacks, and makes `totalDeposited` and * `totalDepositedBdv` significantly more MEV resistant. */ function incrementTotalGerminating( address token, uint256 amount, uint256 bdv, LibGerminate.Germinate germ ) internal { AppStorage storage s = LibAppStorage.diamondStorage(); Storage.TotalGerminating storage germinate; // verify germ is valid if (germ == LibGerminate.Germinate.ODD) { germinate = s.oddGerminating; } else if (germ == LibGerminate.Germinate.EVEN) { germinate = s.evenGerminating; } else { revert("invalid germinationMode"); // should not ever get here } // increment germinating amount and bdv. germinate.deposited[token].amount = germinate.deposited[token].amount.add( amount.toUint128() ); germinate.deposited[token].bdv = germinate.deposited[token].bdv.add(bdv.toUint128()); // emit event. emit LibGerminate.TotalGerminatingBalanceChanged( s.season.current, token, int256(amount), int256(bdv) ); } /** * @notice Decrement the total amount and bdv of `token` germinating in the Silo. * @dev `decrementTotalGerminating` should be used when removing deposits * that are < 2 seasons old. */ function decrementTotalGerminating( address token, uint256 amount, uint256 bdv, LibGerminate.Germinate germ ) internal { AppStorage storage s = LibAppStorage.diamondStorage(); Storage.TotalGerminating storage germinate; // verify germ is valid if (germ == LibGerminate.Germinate.ODD) { germinate = s.oddGerminating; } else if (germ == LibGerminate.Germinate.EVEN) { germinate = s.evenGerminating; } else { revert("invalid germinationMode"); // should not ever get here } // decrement germinating amount and bdv. germinate.deposited[token].amount = germinate.deposited[token].amount.sub( amount.toUint128() ); germinate.deposited[token].bdv = germinate.deposited[token].bdv.sub(bdv.toUint128()); emit LibGerminate.TotalGerminatingBalanceChanged( LibGerminate.getSeasonGerminationState() == germ ? s.season.current : s.season.current - 1, token, -int256(amount), -int256(bdv) ); } /** * @notice Increment the total bdv of `token` germinating in the Silo. Used in Enroot. */ function incrementTotalGerminatingBdv( address token, uint256 bdv, LibGerminate.Germinate germ ) internal { AppStorage storage s = LibAppStorage.diamondStorage(); if (germ == LibGerminate.Germinate.ODD) { // increment odd germinating s.oddGerminating.deposited[token].bdv = s.oddGerminating.deposited[token].bdv.add( bdv.toUint128() ); } else if (germ == LibGerminate.Germinate.EVEN) { // increment even germinating s.evenGerminating.deposited[token].bdv = s.evenGerminating.deposited[token].bdv.add( bdv.toUint128() ); } else { revert("invalid germinationMode"); // should not ever get here } emit LibGerminate.TotalGerminatingBalanceChanged( LibGerminate.getSeasonGerminationState() == germ ? s.season.current : s.season.current - 1, token, 0, int256(bdv) ); } //////////////////////// ACCOUNTING: TOTALS //////////////////////// /** * @dev Increment the total amount and bdv of `token` deposited in the Silo. * @dev `IncrementTotalDeposited` should be used when removing deposits that are * >= 2 seasons old (ex. when a user converts). */ function incrementTotalDeposited(address token, uint256 amount, uint256 bdv) internal { AppStorage storage s = LibAppStorage.diamondStorage(); s.siloBalances[token].deposited = s.siloBalances[token].deposited.add(amount.toUint128()); s.siloBalances[token].depositedBdv = s.siloBalances[token].depositedBdv.add( bdv.toUint128() ); } /** * @notice Decrement the total amount and bdv of `token` deposited in the Silo. * @dev `decrementTotalDeposited` should be used when removing deposits that are * >= 2 seasons old. */ function decrementTotalDeposited(address token, uint256 amount, uint256 bdv) internal { AppStorage storage s = LibAppStorage.diamondStorage(); s.siloBalances[token].deposited = s.siloBalances[token].deposited.sub(amount.toUint128()); s.siloBalances[token].depositedBdv = s.siloBalances[token].depositedBdv.sub( bdv.toUint128() ); } /** * @notice Increment the total bdv of `token` deposited in the Silo. Used in Enroot. */ function incrementTotalDepositedBdv(address token, uint256 bdv) internal { AppStorage storage s = LibAppStorage.diamondStorage(); s.siloBalances[token].depositedBdv = s.siloBalances[token].depositedBdv.add( bdv.toUint128() ); } //////////////////////// ADD DEPOSIT //////////////////////// /** * @return stalk The amount of Stalk received for this Deposit. * * @dev Calculate the current BDV for `amount` of `token`, then perform * Deposit accounting. */ function deposit( address account, address token, int96 stem, uint256 amount ) internal returns (uint256, LibGerminate.Germinate) { uint256 bdv = beanDenominatedValue(token, amount); return depositWithBDV(account, token, stem, amount, bdv); } /** * @dev Once the BDV received for Depositing `amount` of `token` is known, * add a Deposit for `account` and update the total amount Deposited. * * `s.ss[token].stalkIssuedPerBdv` stores the number of Stalk per BDV for `token`. */ function depositWithBDV( address account, address token, int96 stem, uint256 amount, uint256 bdv ) internal returns (uint256 stalk, LibGerminate.Germinate germ) { require(bdv > 0, "Silo: No Beans under Token."); AppStorage storage s = LibAppStorage.diamondStorage(); // determine whether the deposit is odd or even germinating germ = LibGerminate.getSeasonGerminationState(); // all new deposits will increment total germination. incrementTotalGerminating(token, amount, bdv, germ); addDepositToAccount( account, token, stem, amount, bdv, Transfer.emitTransferSingle ); stalk = bdv.mul(s.ss[token].stalkIssuedPerBdv); } /** * @dev Add `amount` of `token` to a user's Deposit in `stemTipForToken`. Requires a * precalculated `bdv`. * * If a Deposit doesn't yet exist, one is created. Otherwise, the existing * Deposit is updated. * * `amount` & `bdv` are downcasted uint256 -> uint128 to optimize storage cost, * since both values can be packed into one slot. * * Unlike {removeDepositFromAccount}, this function DOES EMIT an * {AddDeposit} event. See {removeDepositFromAccount} for more details. */ function addDepositToAccount( address account, address token, int96 stem, uint256 amount, uint256 bdv, Transfer transferType ) internal { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 depositId = LibBytes.packAddressAndStem(token, stem); // add amount and bdv to the deposits. s.a[account].deposits[depositId].amount = s.a[account].deposits[depositId].amount.add( amount.toUint128() ); s.a[account].deposits[depositId].bdv = s.a[account].deposits[depositId].bdv.add( bdv.toUint128() ); // SafeMath unnecessary b/c crateBDV <= type(uint128).max s.a[account].mowStatuses[token].bdv = s.a[account].mowStatuses[token].bdv.add( bdv.toUint128() ); /** * {addDepositToAccount} is used for both depositing and transferring deposits. * In the case of a deposit, only the {TransferSingle} Event needs to be emitted. * In the case of a transfer, a different {TransferSingle}/{TransferBatch} * Event is emitted in {TokenSilo._transferDeposit(s)}, * and thus, this event is ommited. */ if (transferType == Transfer.emitTransferSingle) { emit TransferSingle( msg.sender, // operator address(0), // from account, // to depositId, // depositID amount // token amount ); } emit AddDeposit(account, token, stem, amount, bdv); } //////////////////////// REMOVE DEPOSIT //////////////////////// /** * @dev Remove `amount` of `token` from a user's Deposit in `stem`. * * A "Crate" refers to the existing Deposit in storage at: * `s.a[account].deposits[token][stem]` * * Partially removing a Deposit should scale its BDV proportionally. For ex. * removing 80% of the tokens from a Deposit should reduce its BDV by 80%. * * During an update, `amount` & `bdv` are cast uint256 -> uint128 to * optimize storage cost, since both values can be packed into one slot. * * This function DOES **NOT** EMIT a {RemoveDeposit} event. This * asymmetry occurs because {removeDepositFromAccount} is called in a loop * in places where multiple deposits are removed simultaneously, including * {TokenSilo-removeDepositsFromAccount} and {TokenSilo-_transferDeposits}. */ function removeDepositFromAccount( address account, address token, int96 stem, uint256 amount ) internal returns (uint256 crateBDV) { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 depositId = LibBytes.packAddressAndStem(token, stem); uint256 crateAmount = s.a[account].deposits[depositId].amount; crateBDV = s.a[account].deposits[depositId].bdv; // if amount is > crateAmount, check if user has a legacy deposit: if (amount > crateAmount) { // get the absolute stem value. uint256 absStem = stem > 0 ? uint256(stem) : uint256(-stem); // only stems with modulo 1e6 can have a legacy deposit. if (absStem.mod(1e6) == 0) { (crateAmount, crateBDV) = migrateLegacyStemDeposit( account, token, stem, crateAmount, crateBDV ); } } require(amount <= crateAmount, "Silo: Crate balance too low."); // Partial remove if (amount < crateAmount) { // round up removal of BDV. (x - 1)/y + 1 // https://stackoverflow.com/questions/17944 uint256 removedBDV = amount.sub(1).mul(crateBDV).div(crateAmount).add(1); uint256 updatedBDV = crateBDV.sub(removedBDV); uint256 updatedAmount = crateAmount.sub(amount); // SafeCast unnecessary b/c updatedAmount <= crateAmount and updatedBDV <= crateBDV, // which are both <= type(uint128).max s.a[account].deposits[depositId].amount = updatedAmount.toUint128(); s.a[account].deposits[depositId].bdv = updatedBDV.toUint128(); s.a[account].mowStatuses[token].bdv = s.a[account].mowStatuses[token].bdv.sub( removedBDV.toUint128() ); return removedBDV; } // Full remove if (crateAmount > 0) delete s.a[account].deposits[depositId]; // SafeMath unnecessary b/c crateBDV <= type(uint128).max s.a[account].mowStatuses[token].bdv = s.a[account].mowStatuses[token].bdv.sub( crateBDV.toUint128() ); } //////////////////////// GETTERS //////////////////////// /** * @dev Calculate the BDV ("Bean Denominated Value") for `amount` of `token`. * * Makes a call to a BDV function defined in the SiloSettings for this * `token`. See {AppStorage.sol:Storage-SiloSettings} for more information. */ function beanDenominatedValue( address token, uint256 amount ) internal view returns (uint256 bdv) { AppStorage storage s = LibAppStorage.diamondStorage(); require(s.ss[token].selector != bytes4(0), "Silo: Token not whitelisted"); (bool success, bytes memory data) = address(this).staticcall( encodeBdvFunction(token, s.ss[token].encodeType, s.ss[token].selector, amount) ); if (!success) { if (data.length == 0) revert(); assembly { revert(add(32, data), mload(data)) } } assembly { bdv := mload(add(data, add(0x20, 0))) } } function encodeBdvFunction( address token, bytes1 encodeType, bytes4 selector, uint256 amount ) internal pure returns (bytes memory callData) { if (encodeType == 0x00) { callData = abi.encodeWithSelector(selector, amount); } else if (encodeType == 0x01) { callData = abi.encodeWithSelector(selector, token, amount); } else { revert("Silo: Invalid encodeType"); } } /** * @dev Locate the `amount` and `bdv` for a user's Deposit in storage. * * Silo V3 Deposits are stored within each {Account} as a mapping of: * `uint256 DepositID => { uint128 amount, uint128 bdv }` * The DepositID is the concatination of the token address and the stem. * * Silo V2 deposits are only usable after a successful migration, see * mowAndMigrate within the Migration facet. * */ function getDeposit( address account, address token, int96 stem ) internal view returns (uint256 amount, uint256 bdv) { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 depositId = LibBytes.packAddressAndStem(token, stem); amount = s.a[account].deposits[depositId].amount; bdv = s.a[account].deposits[depositId].bdv; } /** * @dev Get the number of Stalk per BDV per Season for a whitelisted token. * 6 decimal precision: 1e10 units = 1 stalk per season */ function stalkEarnedPerSeason(address token) internal view returns (uint256) { AppStorage storage s = LibAppStorage.diamondStorage(); return uint256(s.ss[token].stalkEarnedPerSeason); } /** * @dev Get the number of Stalk per BDV for a whitelisted token. Formerly just stalk. */ function stalkIssuedPerBdv(address token) internal view returns (uint256) { AppStorage storage s = LibAppStorage.diamondStorage(); return uint256(s.ss[token].stalkIssuedPerBdv); } /** * @dev returns the cumulative stalk per BDV (stemTip) for a whitelisted token. */ function stemTipForToken( address token ) internal view returns (int96 _stemTip) { AppStorage storage s = LibAppStorage.diamondStorage(); // SafeCast unnecessary because all casted variables are types smaller that int96. _stemTip = s.ss[token].milestoneStem + int96(s.ss[token].stalkEarnedPerSeason).mul( int96(s.season.current).sub(int96(s.ss[token].milestoneSeason)) ); } /** * @dev returns the amount of grown stalk a deposit has earned. */ function grownStalkForDeposit( address account, address token, int96 stem ) internal view returns (uint grownStalk) { // stemTipForToken(token) > depositGrownStalkPerBdv for all valid Deposits int96 _stemTip = stemTipForToken(token); require(stem <= _stemTip, "Silo: Invalid Deposit"); // The check in the above line guarantees that subtraction result is positive // and thus the cast to `uint256` is safe. uint deltaStemTip = uint256(_stemTip.sub(stem)); // no stalk has grown if the stem is equal to the stemTip. if (deltaStemTip == 0) return 0; (, uint bdv) = getDeposit(account, token, stem); grownStalk = deltaStemTip.mul(bdv).div(PRECISION); } /** * @dev returns the amount of grown stalk a deposit would have, based on the stem of the deposit. */ function calculateStalkFromStemAndBdv( address token, int96 grownStalkIndexOfDeposit, uint256 bdv ) internal view returns (int96 grownStalk) { // current latest grown stalk index int96 _stemTipForToken = stemTipForToken(address(token)); return _stemTipForToken.sub(grownStalkIndexOfDeposit).mul(toInt96(bdv)); } /** * @notice returns the grown stalk and germination state of a deposit, * based on the amount of grown stalk it has earned. */ function calculateStemForTokenFromGrownStalk( address token, uint256 grownStalk, uint256 bdv ) internal view returns (int96 stem, LibGerminate.Germinate germ) { LibGerminate.GermStem memory germStem = LibGerminate.getGerminatingStem(token); stem = germStem.stemTip.sub(toInt96(grownStalk.mul(PRECISION).div(bdv))); germ = LibGerminate._getGerminationState(stem, germStem); } /** * @dev returns the amount of grown stalk a deposit would have, based on the stem of the deposit. * Similar to calculateStalkFromStemAndBdv, but has an additional check to prevent division by 0. */ function grownStalkAndBdvToStem( address token, uint256 grownStalk, uint256 bdv ) internal view returns (int96 cumulativeGrownStalk) { // first get current latest grown stalk index int96 _stemTipForToken = stemTipForToken(token); // then calculate how much stalk each individual bdv has grown // there's a > 0 check here, because if you have a small amount of unripe bean deposit, the bdv could // end up rounding to zero, then you get a divide by zero error and can't migrate without losing that deposit // prevent divide by zero error int96 grownStalkPerBdv = bdv > 0 ? toInt96(grownStalk.mul(PRECISION).div(bdv)) : 0; // subtract from the current latest index, so we get the index the deposit should have happened at return _stemTipForToken.sub(grownStalkPerBdv); } /** * @notice internal logic for migrating a legacy deposit. * @dev */ function migrateLegacyStemDeposit( address account, address token, int96 newStem, uint256 crateAmount, uint256 crateBdv ) internal returns (uint256, uint256) { AppStorage storage s = LibAppStorage.diamondStorage(); // divide the newStem by 1e6 to get the legacy stem. uint256 legacyDepositId = LibBytes.packAddressAndStem(token, newStem.div(1e6)); uint256 legacyAmount = s.a[account].legacyV3Deposits[legacyDepositId].amount; uint256 legacyBdv = s.a[account].legacyV3Deposits[legacyDepositId].bdv; crateAmount = crateAmount.add(legacyAmount); crateBdv = crateBdv.add(legacyBdv); delete s.a[account].legacyV3Deposits[legacyDepositId]; // Emit burn events. emit TransferSingle( msg.sender, account, address(0), legacyDepositId, legacyAmount ); emit RemoveDeposit( account, token, newStem.div(1e6), legacyAmount, legacyBdv ); // Emit mint events. emit TransferSingle( msg.sender, address(0), account, LibBytes.packAddressAndStem(token, newStem), legacyAmount ); emit AddDeposit( account, token, newStem, legacyAmount, legacyBdv ); return (crateAmount, crateBdv); } function toInt96(uint256 value) internal pure returns (int96) { require(value <= uint256(type(int96).max), "SafeCast: value doesn't fit in an int96"); return int96(value); } }
/* SPDX-License-Identifier: MIT */ pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import {C} from "../../C.sol"; import {AppStorage, Storage, LibAppStorage} from "contracts/libraries/LibAppStorage.sol"; /** * @title LibWhitelistedTokens * @author Brean, Brendan * @notice LibWhitelistedTokens holds different lists of types of Whitelisted Tokens. * * @dev manages the WhitelistStatuses for all tokens in the Silo in order to track lists. * Note: dewhitelisting a token doesn't remove it's WhitelistStatus entirely–It just modifies it. * Once a token has no more Deposits in the Silo, it's WhitelistStatus should be removed through calling `removeWhitelistStatus`. */ library LibWhitelistedTokens { /** * @notice Emitted when a Whitelis Status is added. */ event AddWhitelistStatus( address token, uint256 index, bool isWhitelisted, bool isWhitelistedLp, bool isWhitelistedWell ); /** * @notice Emitted when a Whitelist Status is removed. */ event RemoveWhitelistStatus( address token, uint256 index ); /** * @notice Emitted when a Whitelist Status is updated. */ event UpdateWhitelistStatus( address token, uint256 index, bool isWhitelisted, bool isWhitelistedLp, bool isWhitelistedWell ); /** * @notice Returns all tokens that are currently or previously in the silo, * including Unripe tokens. * @dev includes Dewhitelisted tokens with existing Deposits. */ function getSiloTokens() internal view returns (address[] memory tokens) { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 numberOfSiloTokens = s.whitelistStatuses.length; tokens = new address[](numberOfSiloTokens); for (uint256 i = 0; i < numberOfSiloTokens; i++) { tokens[i] = s.whitelistStatuses[i].token; } } /** * @notice Returns the current Whitelisted tokens, including Unripe tokens. */ function getWhitelistedTokens() internal view returns (address[] memory tokens) { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 numberOfSiloTokens = s.whitelistStatuses.length; uint256 tokensLength; tokens = new address[](numberOfSiloTokens); for (uint256 i = 0; i < numberOfSiloTokens; i++) { if (s.whitelistStatuses[i].isWhitelisted) { tokens[tokensLength++] = s.whitelistStatuses[i].token; } } assembly { mstore(tokens, tokensLength) } } /** * @notice Returns the current Whitelisted LP tokens. * @dev Unripe LP is not an LP token. */ function getWhitelistedLpTokens() internal view returns (address[] memory tokens) { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 numberOfSiloTokens = s.whitelistStatuses.length; uint256 tokensLength; tokens = new address[](numberOfSiloTokens); for (uint256 i = 0; i < numberOfSiloTokens; i++) { if (s.whitelistStatuses[i].isWhitelistedLp) { // assembly { // mstore(tokens, add(mload(tokens), 1)) // } tokens[tokensLength++] = s.whitelistStatuses[i].token; } } assembly { mstore(tokens, tokensLength) } } /** * @notice Returns the current Whitelisted Well LP tokens. */ function getWhitelistedWellLpTokens() internal view returns (address[] memory tokens) { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 numberOfSiloTokens = s.whitelistStatuses.length; uint256 tokensLength; tokens = new address[](numberOfSiloTokens); for (uint256 i = 0; i < numberOfSiloTokens; i++) { if (s.whitelistStatuses[i].isWhitelistedWell) { tokens[tokensLength++] = s.whitelistStatuses[i].token; } } assembly { mstore(tokens, tokensLength) } } /** * @notice Returns the Whitelist statues for all tokens that have been whitelisted and not manually removed. */ function getWhitelistedStatuses() internal view returns (Storage.WhitelistStatus[] memory _whitelistStatuses) { AppStorage storage s = LibAppStorage.diamondStorage(); _whitelistStatuses = s.whitelistStatuses; } /** * @notice Returns the Whitelist status for a given token. */ function getWhitelistedStatus(address token) internal view returns (Storage.WhitelistStatus memory _whitelistStatus) { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 tokenStatusIndex = findWhitelistStatusIndex(token); _whitelistStatus = s.whitelistStatuses[tokenStatusIndex]; } /** * @notice Adds a Whitelist Status for a given `token`. */ function addWhitelistStatus(address token, bool isWhitelisted, bool isWhitelistedLp, bool isWhitelistedWell) internal { AppStorage storage s = LibAppStorage.diamondStorage(); s.whitelistStatuses.push(Storage.WhitelistStatus( token, isWhitelisted, isWhitelistedLp, isWhitelistedWell )); emit AddWhitelistStatus(token, s.whitelistStatuses.length - 1, isWhitelisted, isWhitelistedLp, isWhitelistedWell); } /** * @notice Modifies the exisiting Whitelist Status of `token`. */ function updateWhitelistStatus(address token, bool isWhitelisted, bool isWhitelistedLp, bool isWhitelistedWell) internal { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 tokenStatusIndex = findWhitelistStatusIndex(token); s.whitelistStatuses[tokenStatusIndex].isWhitelisted = isWhitelisted; s.whitelistStatuses[tokenStatusIndex].isWhitelistedLp = isWhitelistedLp; s.whitelistStatuses[tokenStatusIndex].isWhitelistedWell = isWhitelistedWell; emit UpdateWhitelistStatus( token, tokenStatusIndex, isWhitelisted, isWhitelistedLp, isWhitelistedWell ); } /** * @notice Removes `token`'s Whitelist Status. */ function removeWhitelistStatus(address token) internal { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 tokenStatusIndex = findWhitelistStatusIndex(token); s.whitelistStatuses[tokenStatusIndex] = s.whitelistStatuses[s.whitelistStatuses.length - 1]; s.whitelistStatuses.pop(); emit RemoveWhitelistStatus(token, tokenStatusIndex); } /** * @notice Finds the index of a given `token`'s Whitelist Status. */ function findWhitelistStatusIndex(address token) private view returns (uint256) { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 whitelistedStatusLength = s.whitelistStatuses.length; uint256 i; while (s.whitelistStatuses[i].token != token) { i++; if (i >= whitelistedStatusLength) { revert("LibWhitelistedTokens: Token not found"); } } return i; } /** * @notice checks if a token is whitelisted. * @dev checks whether a token is in the whitelistStatuses array. If it is, * verify whether `isWhitelisted` is set to false. * @param token the token to check. */ function checkWhitelisted(address token) internal view returns (bool isWhitelisted, bool previouslyWhitelisted) { AppStorage storage s = LibAppStorage.diamondStorage(); uint256 whitelistedStatusLength = s.whitelistStatuses.length; uint256 i; while (s.whitelistStatuses[i].token != token) { i++; if (i >= whitelistedStatusLength) { // if the token does not appear in the array // it has not been whitelisted nor dewhitelisted. return (false, false); } } if (s.whitelistStatuses[i].isWhitelisted) { // token is whitelisted. return (true, false); } else { // token has been whitelisted previously. return (false, true); } } }
/* 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": { "contracts/libraries/Convert/LibConvert.sol": { "LibConvert": "0xc119b6d9ca264fc789a6ae69c0e37d6dfe9cff27" } } }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"address","name":"fromToken","type":"address"},{"indexed":false,"internalType":"address","name":"toToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"fromAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"toAmount","type":"uint256"}],"name":"Convert","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"int96","name":"stem","type":"int96"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"bdv","type":"uint256"}],"name":"RemoveDeposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"int96[]","name":"stems","type":"int96[]"},{"indexed":false,"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256[]","name":"bdvs","type":"uint256[]"}],"name":"RemoveDeposits","type":"event"},{"inputs":[{"internalType":"bytes","name":"convertData","type":"bytes"},{"internalType":"int96[]","name":"stems","type":"int96[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"name":"convert","outputs":[{"internalType":"int96","name":"toStem","type":"int96"},{"internalType":"uint256","name":"fromAmount","type":"uint256"},{"internalType":"uint256","name":"toAmount","type":"uint256"},{"internalType":"uint256","name":"fromBdv","type":"uint256"},{"internalType":"uint256","name":"toBdv","type":"uint256"}],"stateMutability":"payable","type":"function"}]
Contract Creation Code
608060405234801561001057600080fd5b50613d09806100206000396000f3fe60806040526004361061001e5760003560e01c8063b362a6e814610023575b600080fd5b6100366100313660046135d4565b610050565b604051610047959493929190613859565b60405180910390f35b600080600080600060026000601e015414156100875760405162461bcd60e51b815260040161007e90613a5c565b60405180910390fd5b6002601e55604051634ae9da6f60e11b81526000908190819073c119b6d9ca264fc789a6ae69c0e37d6dfe9cff27906395d3b4de906100cc908f908f906004016137ed565b60806040518083038186803b1580156100e457600080fd5b505af41580156100f8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061011c9190613592565b995097509093509150866101425760405162461bcd60e51b815260040161007e906139ee565b61014c33836101f2565b61015633846101f2565b610162828b8b8a6103a6565b95509050600061017284886107a5565b90508581116101815785610183565b805b9450610191848887856108a7565b9850336001600160a01b03167f3f7117900f070f33613da64255c3e8a5b791ff071197653712e53fde9c3dab3d84868b8b6040516101d29493929190613707565b60405180910390a250506001601e55509499939850919650945092509050565b60006101fc610983565b905060008061020a85610988565b91509150811561022c5760405162461bcd60e51b815260040161007e90613a93565b6003830154600160d01b900461ffff1663ffffffff8216108015610256575060008163ffffffff16115b8061028457506003830154600160d01b900461ffff1663ffffffff82161480156102845750610284856109ef565b156102925761029285610adf565b600383015463ffffffff9081169060009083168211156102ba576102b7878484610c6d565b90505b6003850154600160c01b810461ffff16600160681b90910463ffffffff16111561035357600385015463ffffffff600160681b909104811690841611158061032b57506001600160a01b03871660009081526031860160205260409020600a0154600160601b900463ffffffff1615155b801561034357508163ffffffff168363ffffffff1611155b1561035357610353878483610eb3565b61035d8787611180565b506001600160a01b0390951660009081526031909301602052505060409020600a01805463ffffffff909316600160201b0267ffffffff00000000199093169290921790915550565b60008083518551146103ca5760405162461bcd60e51b815260040161007e9061393c565b6103d2613435565b600080600090506000885167ffffffffffffffff811180156103f357600080fd5b5060405190808252806020026020018201604052801561041d578160200160208202803683370190505b5090506000895167ffffffffffffffff8111801561043a57600080fd5b50604051908082528060200260200182016040528015610464578160200160208202803683370190505b50905060006104728c611260565b90505b8a5184108015610486575085515189115b15610618578a848151811061049757fe5b6020026020010151600b0b8160000151600b0b136104ba57600190930192610475565b886104de8b86815181106104ca57fe5b602090810291909101015188515190611298565b1061050a578551516104f1908a906112f9565b8a85815181106104fd57fe5b6020026020010181815250505b61053c338d8d878151811061051b57fe5b60200260200101518d888151811061052f57fe5b6020026020010151611344565b94508483858151811061054b57fe5b6020026020010181815250506105906105848c868151811061056957fe5b6020026020010151836020015161057f896116bb565b611703565b87516020015190611298565b86516020015289516105bc908b90869081106105a857fe5b602090810291909101015187515190611298565b8651528551604001516105cf9086611298565b8651604001528a516105f6908d908d90879081106105e957fe5b602002602001015161175c565b82858151811061060257fe5b6020908102919091010152600190930192610475565b8a518410156106465760008a858151811061062f57fe5b602002602001018181525050836001019350610618565b8b6001600160a01b0316336001600160a01b03167f6008478fd0513693018a0ac8771ada053137941c0d833295a27629af7a3ab56b8d8d8a6000015160000151886040516106979493929190613749565b60405180910390a360006001600160a01b0316336001600160a01b0316336001600160a01b03167f4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb858e6040516106ef9291906137bf565b60405180910390a450508351518714905061071c5760405162461bcd60e51b815260040161007e90613881565b82518051604090910151610731918b91611779565b6001600160a01b038916600090815260396020526040908190205484519091015161078891339161078391610777919063ffffffff600160401b90910481169061186c16565b86516020015190611298565b6118c5565b505090516020810151604090910151909890975095505050505050565b6000806107b0610983565b6001600160a01b038516600090815260398201602052604090205490915060e01b6001600160e01b0319166107f75760405162461bcd60e51b815260040161007e90613a25565b6001600160a01b038416600090815260398201602052604081205481903090610830908890600160e01b810460f81b9060e01b89611aae565b60405161083d91906136ce565b600060405180830381855afa9150503d8060008114610878576040519150601f19603f3d011682016040523d82523d6000602084013e61087d565b606091505b50915091508161089a57805161089257600080fd5b805181602001fd5b6020015195945050505050565b600080831180156108b85750600084115b6108d45760405162461bcd60e51b815260040161007e90613ac3565b60006108e1868486611b4c565b909250905060028160028111156108f457fe5b141561093057610905868686611b9d565b61092b33610926856109206109198b611c54565b899061186c565b90611298565b611c90565b61096b565b61093c86868684611dc4565b6109613361095b61095661094f8a611c54565b889061186c565b6116bb565b83611f4f565b61096b3384611c90565b61097a338784888860006121da565b50949350505050565b600090565b6000806000610995610983565b6001600160a01b03851660009081526031820160205260409020600a0154600160201b900463ffffffff169250905081158015906109e757506003810154600160c01b900461ffff1663ffffffff8316105b925050915091565b6000806109fa610983565b90506000610a06612463565b905060005b8151811015610ad2576000836031016000876001600160a01b03166001600160a01b03168152602001908152602001600020601a016000848481518110610a4e57fe5b6020908102919091018101516001600160a01b03168252810191909152604001600090812054600b90810b925082900b1315610ac957620f4240600b0b610ab482610aab868681518110610a9e57fe5b6020026020010151612521565b600b0b906125d9565b600b0b12610ac9576001945050505050610ada565b50600101610a0b565b506000925050505b919050565b6000610ae9610983565b90506000610af5612463565b905060005b8151811015610c67576000836031016000866001600160a01b03166001600160a01b03168152602001908152602001600020601a016000848481518110610b3d57fe5b6020908102919091018101516001600160a01b0316825281019190915260400160002054600b90810b900b1315610c5f576001600160a01b038416600090815260318401602052604081208351610bd492620f424092601a0191869086908110610ba357fe5b6020908102919091018101516001600160a01b0316825281019190915260400160002054600b90810b900b906126a9565b836031016000866001600160a01b03166001600160a01b03168152602001908152602001600020601a016000848481518110610c0c57fe5b60200260200101516001600160a01b03166001600160a01b0316815260200190815260200160002060000160006101000a8154816001600160601b030219169083600b0b6001600160601b031602179055505b600101610afa565b50505050565b600080610c78610983565b90506000610c8585612774565b9050600080610c9488846127a5565b915091506000806000846001600160801b0316118015610cd35750610cc463ffffffff808a169060019061283216565b63ffffffff168963ffffffff16105b15610d3457600080610ce78c8c888a612883565b915091508592508193508198508b6001600160a01b0316600080516020613be7833981519152846001600160801b031660000383604051610d2992919061381c565b60405180910390a250505b6001600160801b03831615610dd657600080610d678c610d5f63ffffffff808f169060019061283216565b878a15612883565b9092509050610d7f6001600160801b038416866129bd565b9250610d946001600160801b038516836129bd565b93508b6001600160a01b0316600080516020613be7833981519152846001600160801b031660000383604051610dcb92919061381c565b60405180910390a250505b6001600160801b03811615610ea6576001600160a01b038a166000908152603187016020526040902060080154610e16906001600160801b038316611298565b6001600160a01b038b16600090815260318801602052604090206008810191909155600e0154610e4f906001600160801b038416611298565b6001600160a01b038b16600081815260318901602052604090819020600e01929092559051600080516020613cb483398151915290610e9d906001600160801b038086169190871690613830565b60405180910390a25b5050505050509392505050565b6000610ebd610983565b600381015490915063ffffffff808516600160481b909204161115610f3857610ee584612a21565b6001600160a01b0385166000908152603183016020526040902060148101919091556003820154600a909101805463ffffffff60401b1916600160201b90920463ffffffff16600160401b029190911790555b6001600160a01b03841660009081526031820160205260409020600e0154610fb35760038101546001600160a01b038516600090815260319092016020526040909120600a01805463ffffffff60401b1916600160681b90920463ffffffff16600160401b029190911763ffffffff60601b1916905561117b565b6003810154600160881b900460ff161561111e57600381015463ffffffff808516600160681b9092041611156110b5576003810180546001600160a01b03861660009081526031840160205260409020600a8101805463ffffffff60601b1916600160681b9384900463ffffffff908116600160601b0291909117909155600e820154601290920191909155915485831691900482166000190190911614156110b5576001600160801b038216156110b5576001600160a01b0384166000908152603182016020526040902060120154611096906001600160801b0384166112f9565b6001600160a01b03851660009081526031830160205260409020601201555b6003810154600160201b810463ffffffff908116600160681b909204161415611119576003810154600160201b900463ffffffff166000908152603d820160209081526040808320546001600160a01b038816845260318501909252909120601301555b610c67565b6001600160a01b03841660009081526031820160205260409020600a0154600160601b900463ffffffff1615610c67576001600160a01b03841660009081526031820160205260409020600a01805463ffffffff60601b19169055505b505050565b600061118a610983565b9050600061119783612521565b6001600160a01b03858116600090815260318501602090815260408083209388168352601a90930190522054909150600b81900b90600160601b90046001600160801b031680156112085782600b0b82600b0b14156111f9575050505061125c565b61120886610926848685612c3e565b50506001600160a01b0380851660009081526031909301602090815260408085209286168552601a90920190529091208054600b9290920b6001600160601b03166001600160601b03199092169190911790555b5050565b61126861346f565b61127182612521565b600b90810b900b6020820181905261128a908390612c4b565b600b90810b900b8152919050565b6000828201838110156112f0576040805162461bcd60e51b815260206004820152601b60248201527a536166654d6174683a206164646974696f6e206f766572666c6f7760281b604482015290519081900360640190fd5b90505b92915050565b60008282111561133e576040805162461bcd60e51b815260206004820152601e6024820152600080516020613c70833981519152604482015290519081900360640190fd5b50900390565b60008061134f610983565b9050600061135d868661175c565b6001600160a01b03881660009081526031840160209081526040808320848452601d019091529020546001600160801b03600160801b82048116955091925016808511156113e95760008087600b0b136113bd5786600003600b0b6113c2565b86600b0b5b90506113d181620f4240612c65565b6113e7576113e28989898589612cc7565b955091505b505b808511156114095760405162461bcd60e51b815260040161007e906139b7565b808510156115da5760006114366001610920846114308961142a8c866112f9565b9061186c565b90612e96565b9050600061144486836112f9565b9050600061145284896112f9565b905061145d816116bb565b6001600160a01b038c1660009081526031880160209081526040808320898452601d01909152902080546001600160801b0319166001600160801b03929092169190911790556114ac826116bb565b6001600160a01b038c1660009081526031880160209081526040808320898452601d01909152902080546001600160801b03928316600160801b0292169190911790556115766114fb846116bb565b8760310160008e6001600160a01b03166001600160a01b03168152602001908152602001600020601a0160008d6001600160a01b03166001600160a01b03168152602001908152602001600020600001600c9054906101000a90046001600160801b03166001600160801b0316612efa90919063ffffffff16565b6001600160a01b03808d166000908152603190980160209081526040808a20928e168a52601a909201905290962080546001600160801b0397909716600160601b02600160601b600160e01b0319909716969096179095555093506116b392505050565b801561160a576001600160a01b03881660009081526031840160209081526040808320858452601d019091528120555b611658611616856116bb565b6001600160a01b038a811660009081526031870160209081526040808320938d168352601a90930190522054600160601b90046001600160801b031690612efa565b6001600160a01b03808a166000908152603190950160209081526040808720928b168752601a909201905290932080546001600160801b0394909416600160601b02600160601b600160e01b03199094169390931790925550505b949350505050565b6000600160801b82106116ff5760405162461bcd60e51b8152600401808060200182810382526027815260200180613bc06027913960400191505060405180910390fd5b5090565b600080611748620f42406117398561171f600b89900b8a612f51565b600b0b6001600160801b0316612fc990919063ffffffff16565b6001600160801b031690613043565b6001600160801b03169150505b9392505050565b6001600160601b031660609190911b6001600160601b0319161790565b6000611783610983565b90506117bb611791846116bb565b6001600160a01b03861660009081526038840160205260409020546001600160801b031690612efa565b6001600160a01b0385166000908152603883016020526040902080546001600160801b0319166001600160801b03929092169190911790556118306117ff836116bb565b6001600160a01b0386166000908152603884016020526040902054600160801b90046001600160801b031690612efa565b6001600160a01b03909416600090815260389091016020526040902080546001600160801b03948516600160801b029416939093179092555050565b60008261187b575060006112f3565b8282028284828161188857fe5b04146112f05760405162461bcd60e51b8152600401808060200182810382526021815260200180613c286021913960400191505060405180910390fd5b6000806118d0610983565b9050826118e15760009150506112f3565b601b810154601d8201546118fa9190611430908661186c565b6001600160a01b03851660009081526031830160205260409020600e0154909250821115611943576001600160a01b03841660009081526031820160205260409020600e015491505b601b81015461195290846112f9565b601b8201556001600160a01b038416600090815260318201602052604090206008015461197f90846112f9565b6001600160a01b0385166000908152603183016020526040902060080155601d8101546119ac90836112f9565b601d8201556001600160a01b03841660009081526031820160205260409020600e01546119d990836112f9565b6001600160a01b03851660009081526031830160205260409020600e8101829055601201541115611a70576001600160a01b03841660009081526031820160205260408120600e810154601290910154611a32916112f9565b6001600160a01b03861660009081526031840160205260409020600e810154601290910155601a830154909150611a6990826112f9565b601a830155505b836001600160a01b0316600080516020613cb48339815191528460000384600003604051611a9f929190613830565b60405180910390a25092915050565b60606001600160f81b03198416611b0a578282604051602401611ad19190613b17565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915290506116b3565b600160f81b6001600160f81b031985161415611b3457828583604051602401611ad1929190613730565b60405162461bcd60e51b815260040161007e90613985565b6000806000611b5a86611260565b9050611b86611b78611b738661143089620f424061186c565b6130ba565b6020830151600b0b90612f51565b9250611b9283826130e8565b915050935093915050565b6000611ba7610983565b9050611bdf611bb5846116bb565b6001600160a01b03861660009081526038840160205260409020546001600160801b0316906129bd565b6001600160a01b0385166000908152603883016020526040902080546001600160801b0319166001600160801b0392909216919091179055611830611c23836116bb565b6001600160a01b0386166000908152603884016020526040902054600160801b90046001600160801b0316906129bd565b600080611c5f610983565b6001600160a01b0393909316600090815260399390930160205250506040902054600160401b900463ffffffff1690565b6000611c9a610983565b601d810154909150600090611cc257611cbb611cb461314e565b849061186c565b9050611cde565b601b820154601d830154611cdb9190611430908661186c565b90505b601b820154611ced9084611298565b601b8301556001600160a01b0384166000908152603183016020526040902060080154611d1a9084611298565b6001600160a01b0385166000908152603184016020526040902060080155601d820154611d479082611298565b601d8301556001600160a01b03841660009081526031830160205260409020600e0154611d749082611298565b6001600160a01b038516600081815260318501602052604090819020600e01929092559051600080516020613cb483398151915290611db69086908590613830565b60405180910390a250505050565b6000611dce610983565b9050600080836002811115611ddf57fe5b1415611def575060e18101611e25565b6001836002811115611dfd57fe5b1415611e0d575060e28101611e25565b60405162461bcd60e51b815260040161007e9061390b565b611e59611e31866116bb565b6001600160a01b0388166000908152602084905260409020546001600160801b0316906129bd565b6001600160a01b038716600090815260208390526040902080546001600160801b0319166001600160801b0392909216919091179055611eca611e9b856116bb565b6001600160a01b038816600090815260208490526040902054600160801b90046001600160801b0316906129bd565b6001600160a01b0387166000818152602084905260409081902080546001600160801b03948516600160801b029416939093179092556003840154915190917f99f70d4286db852579c7e4c4e3d46125005d363d480494fec6524240ade1e00e91611f3f9163ffffffff169089908990613b20565b60405180910390a2505050505050565b6000611f59610983565b90506000826002811115611f6957fe5b1415611fe0576001600160a01b03841660009081526031820160205260409020601c0154611fa0906001600160801b0316846129bd565b6001600160a01b03851660009081526031830160205260409020601c0180546001600160801b0319166001600160801b0392909216919091179055612051565b6001600160a01b03841660009081526031820160205260409020601c015461201890600160801b90046001600160801b0316846129bd565b6001600160a01b03851660009081526031830160205260409020601c0180546001600160801b03928316600160801b0292169190911790555b600381015463ffffffff1682600281111561206857fe5b612070613157565b600281111561207b57fe5b14156120ec5763ffffffff808216600090815260e3840160205260409020546120b2916001600160801b039091169086906129bd16565b63ffffffff8216600090815260e384016020526040902080546001600160801b0319166001600160801b0392909216919091179055612169565b61210163ffffffff8083169060019061283216565b63ffffffff808216600090815260e385016020526040902054919250612133916001600160801b03169086906129bd16565b63ffffffff8216600090815260e384016020526040902080546001600160801b0319166001600160801b03929092169190911790555b846001600160a01b0316600080516020613be78339815191528585604051612192929190613afa565b60405180910390a27f3dd97efd4911891b98b28287922dd7351872382b548b549517e183ee6544c74381856040516121cb929190613b3e565b60405180910390a15050505050565b60006121e4610983565b905060006121f2878761175c565b9050612238612200866116bb565b6001600160a01b038a1660009081526031850160209081526040808320868452601d019091529020546001600160801b0316906129bd565b6001600160a01b03891660009081526031840160209081526040808320858452601d01909152902080546001600160801b0319166001600160801b03929092169190911790556122c961228a856116bb565b6001600160a01b038a1660009081526031850160209081526040808320868452601d01909152902054600160801b90046001600160801b0316906129bd565b6001600160a01b03891660009081526031840160209081526040808320858452601d01909152902080546001600160801b03928316600160801b02921691909117905561235a612318856116bb565b6001600160a01b038a811660009081526031860160209081526040808320938d168352601a90930190522054600160601b90046001600160801b0316906129bd565b6001600160a01b03808a1660009081526031850160209081526040808320938c168352601a909301905290812080546001600160801b0393909316600160601b02600160601b600160e01b0319909316929092179091558360018111156123bd57fe5b141561240a57876001600160a01b031660006001600160a01b0316336001600160a01b0316600080516020613ba08339815191528489604051612401929190613830565b60405180910390a45b866001600160a01b0316886001600160a01b03167ff4d42fc7416f300569832aee6989201c613d31d64b823327915a6a33fe7afa558888886040516124519392919061383e565b60405180910390a35050505050505050565b6060600061246f610983565b60e48101549091508067ffffffffffffffff8111801561248e57600080fd5b506040519080825280602002602001820160405280156124b8578160200160208202803683370190505b50925060005b8181101561251b578260e40181815481106124d557fe5b60009182526020909120015484516001600160a01b03909116908590839081106124fb57fe5b6001600160a01b03909216602092830291909101909101526001016124be565b50505090565b60008061252c610983565b6001600160a01b038416600090815260398201602052604090205460038201549192506125a9916125749163ffffffff918216600b0b91600160601b909104811690612f5116565b6001600160a01b038516600090815260398401602052604090205463ffffffff600160201b9091048116600b0b91906126a916565b6001600160a01b03909316600090815260399091016020526040902054600160801b9004600b0b91909101919050565b600081600b0b60001415612634576040805162461bcd60e51b815260206004820181905260248201527f5369676e6564536166654d6174683a206469766973696f6e206279207a65726f604482015290519081900360640190fd5b81600b0b6000191480156126535750600b83900b60016001605f1b0319145b1561268f5760405162461bcd60e51b8152600401808060200182810382526021815260200180613c076021913960400191505060405180910390fd5b600082600b0b84600b0b816126a057fe5b05949350505050565b600082600b0b600014156126bf575060006112f3565b82600b0b6000191480156126de5750600b82900b60016001605f1b0319145b1561271a5760405162461bcd60e51b8152600401808060200182810382526027815260200180613c496027913960400191505060405180910390fd5b6000828402905082600b0b84600b0b82600b0b8161273457fe5b05600b0b146112f05760405162461bcd60e51b8152600401808060200182810382526027815260200180613c496027913960400191505060405180910390fd5b600061278b63ffffffff8084169060029061317f16565b63ffffffff161561279d5760016112f3565b600092915050565b60008060006127b2610983565b905083156127f5576001600160a01b03851660009081526031820160205260409020601c01546001600160801b038082169450600160801b90910416915061282a565b6001600160a01b03851660009081526031820160205260409020601c01546001600160801b03600160801b8204811694501691505b509250929050565b60008263ffffffff168263ffffffff16111561133e576040805162461bcd60e51b815260206004820152601e6024820152600080516020613c70833981519152604482015290519081900360640190fd5b6000806000612890610983565b905061289c86866131eb565b925083156128d6576001600160a01b03871660009081526031820160205260408120601c0180546001600160801b03191690559150612905565b6001600160a01b03871660009081526031820160205260409020601c0180546001600160801b03169055600191505b63ffffffff808716600090815260e383016020526040902054612936916001600160801b03909116908790612efa16565b63ffffffff878116600090815260e384016020526040902080546001600160801b0319166001600160801b03938416179081905561298092600160801b90910416908590612efa16565b63ffffffff909616600090815260e39091016020526040902080546001600160801b03968716600160801b02961695909517909455949293505050565b60008282016001600160801b0380851690821610156112f0576040805162461bcd60e51b815260206004820152601b60248201527a536166654d6174683a206164646974696f6e206f766572666c6f7760281b604482015290519081900360640190fd5b600080612a2c610983565b6001600160a01b038416600090815260318201602052604081206014810154600a82015490955092935091600160601b900463ffffffff1615612b5457600a820154600160401b810463ffffffff908116600160601b909204161415612a9757506013810154612abc565b50600a810154600160401b900463ffffffff166000908152603d830160205260409020545b6001600160a01b03851660009081526031840160209081526040808320600a0154600160601b900463ffffffff168352603d860190915290205481811115612b4e576001600160a01b03861660009081526031850160205260409020601201549091829190820390612b4a90612b439069d3c21bcecceda10000009061143090859061186c565b8790611298565b9550505b50612b90565b506001600160a01b03841660009081526031830160209081526040808320600a0154600160401b900463ffffffff168352603d85019091529020545b612b99856132a2565b600384015463ffffffff918216600160201b9091049091161115612c3657600383015463ffffffff600160201b90910481166000908152603d850160205260408120549091612beb919084906112f916565b6001600160a01b03871660009081526031860160205260409020600e0154909150612c3290612c2b9069d3c21bcecceda10000009061143090859061186c565b8690611298565b9450505b505050919050565b60006116b3848484611703565b60006112f082612c5a856132e1565b63ffffffff166133f8565b6000808211612cb6576040805162461bcd60e51b8152602060048201526018602482015277536166654d6174683a206d6f64756c6f206279207a65726f60401b604482015290519081900360640190fd5b818381612cbf57fe5b069392505050565b6000806000612cd4610983565b90506000612cf288612ced600b8a900b620f42406125d9565b61175c565b6001600160a01b038a16600090815260318401602090815260408083208484526019019091529020549091506001600160801b0380821691600160801b900416612d3c8883611298565b9750612d488782611298565b6001600160a01b038c166000818152603187016020908152604080832088845260190190915280822082905551929950913390600080516020613ba083398151915290612d989088908890613830565b60405180910390a46001600160a01b03808b16908c167f153f0425cb9f489d8ca1232a9a790fb1ee212c4d80bb8cf8c83b0f5b203bab1c612de0600b8d900b620f42406125d9565b8585604051612df19392919061383e565b60405180910390a36001600160a01b038b16600033600080516020613ba0833981519152612e1f8e8e61175c565b86604051612e2e929190613830565b60405180910390a4896001600160a01b03168b6001600160a01b03167ff4d42fc7416f300569832aee6989201c613d31d64b823327915a6a33fe7afa558b8585604051612e7d9392919061383e565b60405180910390a3509599949850939650505050505050565b6000808211612ee9576040805162461bcd60e51b815260206004820152601a602482015279536166654d6174683a206469766973696f6e206279207a65726f60301b604482015290519081900360640190fd5b818381612ef257fe5b049392505050565b6000826001600160801b0316826001600160801b0316111561133e576040805162461bcd60e51b815260206004820152601e6024820152600080516020613c70833981519152604482015290519081900360640190fd5b6000818303600b83900b8213801590612f70575083600b0b81600b0b13155b80612f8e5750600083600b0b128015612f8e575083600b0b81600b0b135b6112f05760405162461bcd60e51b8152600401808060200182810382526024815260200180613c906024913960400191505060405180910390fd5b60006001600160801b038316612fe1575060006112f3565b8282026001600160801b038084169080861690831681612ffd57fe5b046001600160801b0316146112f05760405162461bcd60e51b8152600401808060200182810382526021815260200180613c286021913960400191505060405180910390fd5b600080826001600160801b03161161309f576040805162461bcd60e51b815260206004820152601a602482015279536166654d6174683a206469766973696f6e206279207a65726f60301b604482015290519081900360640190fd5b816001600160801b0316836001600160801b031681612ef257fe5b60006b7fffffffffffffffffffffff8211156116ff5760405162461bcd60e51b815260040161007e906138c4565b60008160000151600b0b83600b0b1215613104575060026112f3565b8160200151600b0b83600b0b14156131335761311e6133fd565b61312957600161312c565b60005b90506112f3565b61313b6133fd565b61314657600061312c565b5060016112f3565b64e8d4a5100090565b600080613162610983565b60038101549091506131799063ffffffff1661341f565b91505090565b6000808263ffffffff16116131d6576040805162461bcd60e51b8152602060048201526018602482015277536166654d6174683a206d6f64756c6f206279207a65726f60401b604482015290519081900360640190fd5b8163ffffffff168363ffffffff1681612cbf57fe5b6000806131f6610983565b63ffffffff8516600090815260e3820160205260409020549091506001600160801b03848116911614156132535763ffffffff8416600090815260e382016020526040902054600160801b90046001600160801b0316915061329b565b63ffffffff808516600090815260e38301602052604090205461329891610956916001600160801b03808216926114309289831692600160801b909104169061186c16565b91505b5092915050565b6000806132ad610983565b6001600160a01b03939093166000908152603193909301602052505060409020600a0154600160201b900463ffffffff1690565b6000806132ec610983565b60038101546001600160a01b038516600090815260398301602052604090205491925063ffffffff908116600160601b909204161015613355576001600160a01b0383166000908152603982016020526040902054600160201b900463ffffffff1691506133f2565b6001600160a01b0383166000908152603982016020526040812054600160e81b9004600290810b919082900b126133bc576001600160a01b0384166000908152603983016020526040902054600282900b600160201b90910463ffffffff160392506133f0565b6001600160a01b038416600090815260398301602052604081205463ffffffff600160201b909104169082900360020b0192505b505b50919050565b900390565b600080613408610983565b60038101549091506131799063ffffffff16612774565b600061342a82612774565b61279d5760016112f3565b6040518060800160405280613448613486565b8152602001613455613486565b8152602001613462613486565b8152602001600081525090565b604080518082019091526000808252602082015290565b60405180606001604052806000815260200160008152602001600081525090565b80516001600160a01b0381168114610ada57600080fd5b600082601f8301126134ce578081fd5b813560206134e36134de83613b81565b613b5d565b82815281810190858301838502870184018810156134ff578586fd5b855b8581101561352b57813580600b0b8114613519578788fd5b84529284019290840190600101613501565b5090979650505050505050565b600082601f830112613548578081fd5b813560206135586134de83613b81565b8281528181019085830183850287018401881015613574578586fd5b855b8581101561352b57813584529284019290840190600101613576565b600080600080608085870312156135a7578384fd5b6135b0856134a7565b93506135be602086016134a7565b6040860151606090960151949790965092505050565b600080600080606085870312156135e9578384fd5b843567ffffffffffffffff80821115613600578586fd5b818701915087601f830112613613578586fd5b813581811115613621578687fd5b886020828501011115613632578687fd5b60209283019650945090860135908082111561364c578384fd5b613658888389016134be565b9350604087013591508082111561366d578283fd5b5061367a87828801613538565b91505092959194509250565b6000815180845260208085019450808401835b838110156136b557815187529582019590820190600101613699565b509495945050505050565b600381106136ca57fe5b9052565b60008251815b818110156136ee57602081860181015185830152016136d4565b818111156136fc5782828501525b509190910192915050565b6001600160a01b0394851681529290931660208301526040820152606081019190915260800190565b6001600160a01b03929092168252602082015260400190565b6080808252855190820181905260009060209060a0840190828901845b82811015613785578151600b0b84529284019290840190600101613766565b505050838103828501526137998188613686565b91505084604084015282810360608401526137b48185613686565b979650505050505050565b6000604082526137d26040830185613686565b82810360208401526137e48185613686565b95945050505050565b60006020825282602083015282846040840137818301604090810191909152601f909201601f19160101919050565b8281526040810161175560208301846136c0565b918252602082015260400190565b600b9390930b83526020830191909152604082015260600190565b600b9590950b8552602085019390935260408401919091526060830152608082015260a00190565b60208082526023908201527f436f6e766572743a204e6f7420656e6f75676820746f6b656e732072656d6f7660408201526232b21760e91b606082015260800190565b60208082526027908201527f53616665436173743a2076616c756520646f65736e27742066697420696e2061604082015266371034b73a1c9b60c91b606082015260800190565b602080825260179082015276696e76616c6964206765726d696e6174696f6e4d6f646560481b604082015260600190565b60208082526029908201527f436f6e766572743a207374656d732c20616d6f756e7473206172652064696666604082015268103632b733ba34399760b91b606082015260800190565b60208082526018908201527753696c6f3a20496e76616c696420656e636f64655479706560401b604082015260600190565b6020808252601c908201527f53696c6f3a2043726174652062616c616e636520746f6f206c6f772e00000000604082015260600190565b6020808252601a908201527f436f6e766572743a2046726f6d20616d6f756e7420697320302e000000000000604082015260600190565b6020808252601b908201527f53696c6f3a20546f6b656e206e6f742077686974656c69737465640000000000604082015260600190565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b60208082526016908201527514da5b1bce88135a59dc985d1a5bdb881b995959195960521b604082015260600190565b6020808252601c908201527f436f6e766572743a20424456206f7220616d6f756e7420697320302e00000000604082015260600190565b6001600160801b03831681526040810161175560208301846136c0565b90815260200190565b63ffffffff9390931683526020830191909152604082015260600190565b63ffffffff9290921682526001600160801b0316602082015260400190565b60405181810167ffffffffffffffff81118282101715613b7957fe5b604052919050565b600067ffffffffffffffff821115613b9557fe5b506020908102019056fec3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f6253616665436173743a2076616c756520646f65736e27742066697420696e2031323820626974739c0c70ad39ba6959d6008b9bc651f15ce23613cc1c5ebb4c6ffba0e53a1ea7055369676e6564536166654d6174683a206469766973696f6e206f766572666c6f77536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f775369676e6564536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77536166654d6174683a207375627472616374696f6e206f766572666c6f7700005369676e6564536166654d6174683a207375627472616374696f6e206f766572666c6f77b2d61db64b8ad7535308d2111c78934bc32baf9b7cd3a2e58cba25730003cd58a26469706673582212207cb26d79f6f9b939cd495e5abb7fcc24ed579cc2ac5235905d980941f7d51c2d64736f6c63430007060033
Deployed Bytecode
0x60806040526004361061001e5760003560e01c8063b362a6e814610023575b600080fd5b6100366100313660046135d4565b610050565b604051610047959493929190613859565b60405180910390f35b600080600080600060026000601e015414156100875760405162461bcd60e51b815260040161007e90613a5c565b60405180910390fd5b6002601e55604051634ae9da6f60e11b81526000908190819073c119b6d9ca264fc789a6ae69c0e37d6dfe9cff27906395d3b4de906100cc908f908f906004016137ed565b60806040518083038186803b1580156100e457600080fd5b505af41580156100f8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061011c9190613592565b995097509093509150866101425760405162461bcd60e51b815260040161007e906139ee565b61014c33836101f2565b61015633846101f2565b610162828b8b8a6103a6565b95509050600061017284886107a5565b90508581116101815785610183565b805b9450610191848887856108a7565b9850336001600160a01b03167f3f7117900f070f33613da64255c3e8a5b791ff071197653712e53fde9c3dab3d84868b8b6040516101d29493929190613707565b60405180910390a250506001601e55509499939850919650945092509050565b60006101fc610983565b905060008061020a85610988565b91509150811561022c5760405162461bcd60e51b815260040161007e90613a93565b6003830154600160d01b900461ffff1663ffffffff8216108015610256575060008163ffffffff16115b8061028457506003830154600160d01b900461ffff1663ffffffff82161480156102845750610284856109ef565b156102925761029285610adf565b600383015463ffffffff9081169060009083168211156102ba576102b7878484610c6d565b90505b6003850154600160c01b810461ffff16600160681b90910463ffffffff16111561035357600385015463ffffffff600160681b909104811690841611158061032b57506001600160a01b03871660009081526031860160205260409020600a0154600160601b900463ffffffff1615155b801561034357508163ffffffff168363ffffffff1611155b1561035357610353878483610eb3565b61035d8787611180565b506001600160a01b0390951660009081526031909301602052505060409020600a01805463ffffffff909316600160201b0267ffffffff00000000199093169290921790915550565b60008083518551146103ca5760405162461bcd60e51b815260040161007e9061393c565b6103d2613435565b600080600090506000885167ffffffffffffffff811180156103f357600080fd5b5060405190808252806020026020018201604052801561041d578160200160208202803683370190505b5090506000895167ffffffffffffffff8111801561043a57600080fd5b50604051908082528060200260200182016040528015610464578160200160208202803683370190505b50905060006104728c611260565b90505b8a5184108015610486575085515189115b15610618578a848151811061049757fe5b6020026020010151600b0b8160000151600b0b136104ba57600190930192610475565b886104de8b86815181106104ca57fe5b602090810291909101015188515190611298565b1061050a578551516104f1908a906112f9565b8a85815181106104fd57fe5b6020026020010181815250505b61053c338d8d878151811061051b57fe5b60200260200101518d888151811061052f57fe5b6020026020010151611344565b94508483858151811061054b57fe5b6020026020010181815250506105906105848c868151811061056957fe5b6020026020010151836020015161057f896116bb565b611703565b87516020015190611298565b86516020015289516105bc908b90869081106105a857fe5b602090810291909101015187515190611298565b8651528551604001516105cf9086611298565b8651604001528a516105f6908d908d90879081106105e957fe5b602002602001015161175c565b82858151811061060257fe5b6020908102919091010152600190930192610475565b8a518410156106465760008a858151811061062f57fe5b602002602001018181525050836001019350610618565b8b6001600160a01b0316336001600160a01b03167f6008478fd0513693018a0ac8771ada053137941c0d833295a27629af7a3ab56b8d8d8a6000015160000151886040516106979493929190613749565b60405180910390a360006001600160a01b0316336001600160a01b0316336001600160a01b03167f4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb858e6040516106ef9291906137bf565b60405180910390a450508351518714905061071c5760405162461bcd60e51b815260040161007e90613881565b82518051604090910151610731918b91611779565b6001600160a01b038916600090815260396020526040908190205484519091015161078891339161078391610777919063ffffffff600160401b90910481169061186c16565b86516020015190611298565b6118c5565b505090516020810151604090910151909890975095505050505050565b6000806107b0610983565b6001600160a01b038516600090815260398201602052604090205490915060e01b6001600160e01b0319166107f75760405162461bcd60e51b815260040161007e90613a25565b6001600160a01b038416600090815260398201602052604081205481903090610830908890600160e01b810460f81b9060e01b89611aae565b60405161083d91906136ce565b600060405180830381855afa9150503d8060008114610878576040519150601f19603f3d011682016040523d82523d6000602084013e61087d565b606091505b50915091508161089a57805161089257600080fd5b805181602001fd5b6020015195945050505050565b600080831180156108b85750600084115b6108d45760405162461bcd60e51b815260040161007e90613ac3565b60006108e1868486611b4c565b909250905060028160028111156108f457fe5b141561093057610905868686611b9d565b61092b33610926856109206109198b611c54565b899061186c565b90611298565b611c90565b61096b565b61093c86868684611dc4565b6109613361095b61095661094f8a611c54565b889061186c565b6116bb565b83611f4f565b61096b3384611c90565b61097a338784888860006121da565b50949350505050565b600090565b6000806000610995610983565b6001600160a01b03851660009081526031820160205260409020600a0154600160201b900463ffffffff169250905081158015906109e757506003810154600160c01b900461ffff1663ffffffff8316105b925050915091565b6000806109fa610983565b90506000610a06612463565b905060005b8151811015610ad2576000836031016000876001600160a01b03166001600160a01b03168152602001908152602001600020601a016000848481518110610a4e57fe5b6020908102919091018101516001600160a01b03168252810191909152604001600090812054600b90810b925082900b1315610ac957620f4240600b0b610ab482610aab868681518110610a9e57fe5b6020026020010151612521565b600b0b906125d9565b600b0b12610ac9576001945050505050610ada565b50600101610a0b565b506000925050505b919050565b6000610ae9610983565b90506000610af5612463565b905060005b8151811015610c67576000836031016000866001600160a01b03166001600160a01b03168152602001908152602001600020601a016000848481518110610b3d57fe5b6020908102919091018101516001600160a01b0316825281019190915260400160002054600b90810b900b1315610c5f576001600160a01b038416600090815260318401602052604081208351610bd492620f424092601a0191869086908110610ba357fe5b6020908102919091018101516001600160a01b0316825281019190915260400160002054600b90810b900b906126a9565b836031016000866001600160a01b03166001600160a01b03168152602001908152602001600020601a016000848481518110610c0c57fe5b60200260200101516001600160a01b03166001600160a01b0316815260200190815260200160002060000160006101000a8154816001600160601b030219169083600b0b6001600160601b031602179055505b600101610afa565b50505050565b600080610c78610983565b90506000610c8585612774565b9050600080610c9488846127a5565b915091506000806000846001600160801b0316118015610cd35750610cc463ffffffff808a169060019061283216565b63ffffffff168963ffffffff16105b15610d3457600080610ce78c8c888a612883565b915091508592508193508198508b6001600160a01b0316600080516020613be7833981519152846001600160801b031660000383604051610d2992919061381c565b60405180910390a250505b6001600160801b03831615610dd657600080610d678c610d5f63ffffffff808f169060019061283216565b878a15612883565b9092509050610d7f6001600160801b038416866129bd565b9250610d946001600160801b038516836129bd565b93508b6001600160a01b0316600080516020613be7833981519152846001600160801b031660000383604051610dcb92919061381c565b60405180910390a250505b6001600160801b03811615610ea6576001600160a01b038a166000908152603187016020526040902060080154610e16906001600160801b038316611298565b6001600160a01b038b16600090815260318801602052604090206008810191909155600e0154610e4f906001600160801b038416611298565b6001600160a01b038b16600081815260318901602052604090819020600e01929092559051600080516020613cb483398151915290610e9d906001600160801b038086169190871690613830565b60405180910390a25b5050505050509392505050565b6000610ebd610983565b600381015490915063ffffffff808516600160481b909204161115610f3857610ee584612a21565b6001600160a01b0385166000908152603183016020526040902060148101919091556003820154600a909101805463ffffffff60401b1916600160201b90920463ffffffff16600160401b029190911790555b6001600160a01b03841660009081526031820160205260409020600e0154610fb35760038101546001600160a01b038516600090815260319092016020526040909120600a01805463ffffffff60401b1916600160681b90920463ffffffff16600160401b029190911763ffffffff60601b1916905561117b565b6003810154600160881b900460ff161561111e57600381015463ffffffff808516600160681b9092041611156110b5576003810180546001600160a01b03861660009081526031840160205260409020600a8101805463ffffffff60601b1916600160681b9384900463ffffffff908116600160601b0291909117909155600e820154601290920191909155915485831691900482166000190190911614156110b5576001600160801b038216156110b5576001600160a01b0384166000908152603182016020526040902060120154611096906001600160801b0384166112f9565b6001600160a01b03851660009081526031830160205260409020601201555b6003810154600160201b810463ffffffff908116600160681b909204161415611119576003810154600160201b900463ffffffff166000908152603d820160209081526040808320546001600160a01b038816845260318501909252909120601301555b610c67565b6001600160a01b03841660009081526031820160205260409020600a0154600160601b900463ffffffff1615610c67576001600160a01b03841660009081526031820160205260409020600a01805463ffffffff60601b19169055505b505050565b600061118a610983565b9050600061119783612521565b6001600160a01b03858116600090815260318501602090815260408083209388168352601a90930190522054909150600b81900b90600160601b90046001600160801b031680156112085782600b0b82600b0b14156111f9575050505061125c565b61120886610926848685612c3e565b50506001600160a01b0380851660009081526031909301602090815260408085209286168552601a90920190529091208054600b9290920b6001600160601b03166001600160601b03199092169190911790555b5050565b61126861346f565b61127182612521565b600b90810b900b6020820181905261128a908390612c4b565b600b90810b900b8152919050565b6000828201838110156112f0576040805162461bcd60e51b815260206004820152601b60248201527a536166654d6174683a206164646974696f6e206f766572666c6f7760281b604482015290519081900360640190fd5b90505b92915050565b60008282111561133e576040805162461bcd60e51b815260206004820152601e6024820152600080516020613c70833981519152604482015290519081900360640190fd5b50900390565b60008061134f610983565b9050600061135d868661175c565b6001600160a01b03881660009081526031840160209081526040808320848452601d019091529020546001600160801b03600160801b82048116955091925016808511156113e95760008087600b0b136113bd5786600003600b0b6113c2565b86600b0b5b90506113d181620f4240612c65565b6113e7576113e28989898589612cc7565b955091505b505b808511156114095760405162461bcd60e51b815260040161007e906139b7565b808510156115da5760006114366001610920846114308961142a8c866112f9565b9061186c565b90612e96565b9050600061144486836112f9565b9050600061145284896112f9565b905061145d816116bb565b6001600160a01b038c1660009081526031880160209081526040808320898452601d01909152902080546001600160801b0319166001600160801b03929092169190911790556114ac826116bb565b6001600160a01b038c1660009081526031880160209081526040808320898452601d01909152902080546001600160801b03928316600160801b0292169190911790556115766114fb846116bb565b8760310160008e6001600160a01b03166001600160a01b03168152602001908152602001600020601a0160008d6001600160a01b03166001600160a01b03168152602001908152602001600020600001600c9054906101000a90046001600160801b03166001600160801b0316612efa90919063ffffffff16565b6001600160a01b03808d166000908152603190980160209081526040808a20928e168a52601a909201905290962080546001600160801b0397909716600160601b02600160601b600160e01b0319909716969096179095555093506116b392505050565b801561160a576001600160a01b03881660009081526031840160209081526040808320858452601d019091528120555b611658611616856116bb565b6001600160a01b038a811660009081526031870160209081526040808320938d168352601a90930190522054600160601b90046001600160801b031690612efa565b6001600160a01b03808a166000908152603190950160209081526040808720928b168752601a909201905290932080546001600160801b0394909416600160601b02600160601b600160e01b03199094169390931790925550505b949350505050565b6000600160801b82106116ff5760405162461bcd60e51b8152600401808060200182810382526027815260200180613bc06027913960400191505060405180910390fd5b5090565b600080611748620f42406117398561171f600b89900b8a612f51565b600b0b6001600160801b0316612fc990919063ffffffff16565b6001600160801b031690613043565b6001600160801b03169150505b9392505050565b6001600160601b031660609190911b6001600160601b0319161790565b6000611783610983565b90506117bb611791846116bb565b6001600160a01b03861660009081526038840160205260409020546001600160801b031690612efa565b6001600160a01b0385166000908152603883016020526040902080546001600160801b0319166001600160801b03929092169190911790556118306117ff836116bb565b6001600160a01b0386166000908152603884016020526040902054600160801b90046001600160801b031690612efa565b6001600160a01b03909416600090815260389091016020526040902080546001600160801b03948516600160801b029416939093179092555050565b60008261187b575060006112f3565b8282028284828161188857fe5b04146112f05760405162461bcd60e51b8152600401808060200182810382526021815260200180613c286021913960400191505060405180910390fd5b6000806118d0610983565b9050826118e15760009150506112f3565b601b810154601d8201546118fa9190611430908661186c565b6001600160a01b03851660009081526031830160205260409020600e0154909250821115611943576001600160a01b03841660009081526031820160205260409020600e015491505b601b81015461195290846112f9565b601b8201556001600160a01b038416600090815260318201602052604090206008015461197f90846112f9565b6001600160a01b0385166000908152603183016020526040902060080155601d8101546119ac90836112f9565b601d8201556001600160a01b03841660009081526031820160205260409020600e01546119d990836112f9565b6001600160a01b03851660009081526031830160205260409020600e8101829055601201541115611a70576001600160a01b03841660009081526031820160205260408120600e810154601290910154611a32916112f9565b6001600160a01b03861660009081526031840160205260409020600e810154601290910155601a830154909150611a6990826112f9565b601a830155505b836001600160a01b0316600080516020613cb48339815191528460000384600003604051611a9f929190613830565b60405180910390a25092915050565b60606001600160f81b03198416611b0a578282604051602401611ad19190613b17565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915290506116b3565b600160f81b6001600160f81b031985161415611b3457828583604051602401611ad1929190613730565b60405162461bcd60e51b815260040161007e90613985565b6000806000611b5a86611260565b9050611b86611b78611b738661143089620f424061186c565b6130ba565b6020830151600b0b90612f51565b9250611b9283826130e8565b915050935093915050565b6000611ba7610983565b9050611bdf611bb5846116bb565b6001600160a01b03861660009081526038840160205260409020546001600160801b0316906129bd565b6001600160a01b0385166000908152603883016020526040902080546001600160801b0319166001600160801b0392909216919091179055611830611c23836116bb565b6001600160a01b0386166000908152603884016020526040902054600160801b90046001600160801b0316906129bd565b600080611c5f610983565b6001600160a01b0393909316600090815260399390930160205250506040902054600160401b900463ffffffff1690565b6000611c9a610983565b601d810154909150600090611cc257611cbb611cb461314e565b849061186c565b9050611cde565b601b820154601d830154611cdb9190611430908661186c565b90505b601b820154611ced9084611298565b601b8301556001600160a01b0384166000908152603183016020526040902060080154611d1a9084611298565b6001600160a01b0385166000908152603184016020526040902060080155601d820154611d479082611298565b601d8301556001600160a01b03841660009081526031830160205260409020600e0154611d749082611298565b6001600160a01b038516600081815260318501602052604090819020600e01929092559051600080516020613cb483398151915290611db69086908590613830565b60405180910390a250505050565b6000611dce610983565b9050600080836002811115611ddf57fe5b1415611def575060e18101611e25565b6001836002811115611dfd57fe5b1415611e0d575060e28101611e25565b60405162461bcd60e51b815260040161007e9061390b565b611e59611e31866116bb565b6001600160a01b0388166000908152602084905260409020546001600160801b0316906129bd565b6001600160a01b038716600090815260208390526040902080546001600160801b0319166001600160801b0392909216919091179055611eca611e9b856116bb565b6001600160a01b038816600090815260208490526040902054600160801b90046001600160801b0316906129bd565b6001600160a01b0387166000818152602084905260409081902080546001600160801b03948516600160801b029416939093179092556003840154915190917f99f70d4286db852579c7e4c4e3d46125005d363d480494fec6524240ade1e00e91611f3f9163ffffffff169089908990613b20565b60405180910390a2505050505050565b6000611f59610983565b90506000826002811115611f6957fe5b1415611fe0576001600160a01b03841660009081526031820160205260409020601c0154611fa0906001600160801b0316846129bd565b6001600160a01b03851660009081526031830160205260409020601c0180546001600160801b0319166001600160801b0392909216919091179055612051565b6001600160a01b03841660009081526031820160205260409020601c015461201890600160801b90046001600160801b0316846129bd565b6001600160a01b03851660009081526031830160205260409020601c0180546001600160801b03928316600160801b0292169190911790555b600381015463ffffffff1682600281111561206857fe5b612070613157565b600281111561207b57fe5b14156120ec5763ffffffff808216600090815260e3840160205260409020546120b2916001600160801b039091169086906129bd16565b63ffffffff8216600090815260e384016020526040902080546001600160801b0319166001600160801b0392909216919091179055612169565b61210163ffffffff8083169060019061283216565b63ffffffff808216600090815260e385016020526040902054919250612133916001600160801b03169086906129bd16565b63ffffffff8216600090815260e384016020526040902080546001600160801b0319166001600160801b03929092169190911790555b846001600160a01b0316600080516020613be78339815191528585604051612192929190613afa565b60405180910390a27f3dd97efd4911891b98b28287922dd7351872382b548b549517e183ee6544c74381856040516121cb929190613b3e565b60405180910390a15050505050565b60006121e4610983565b905060006121f2878761175c565b9050612238612200866116bb565b6001600160a01b038a1660009081526031850160209081526040808320868452601d019091529020546001600160801b0316906129bd565b6001600160a01b03891660009081526031840160209081526040808320858452601d01909152902080546001600160801b0319166001600160801b03929092169190911790556122c961228a856116bb565b6001600160a01b038a1660009081526031850160209081526040808320868452601d01909152902054600160801b90046001600160801b0316906129bd565b6001600160a01b03891660009081526031840160209081526040808320858452601d01909152902080546001600160801b03928316600160801b02921691909117905561235a612318856116bb565b6001600160a01b038a811660009081526031860160209081526040808320938d168352601a90930190522054600160601b90046001600160801b0316906129bd565b6001600160a01b03808a1660009081526031850160209081526040808320938c168352601a909301905290812080546001600160801b0393909316600160601b02600160601b600160e01b0319909316929092179091558360018111156123bd57fe5b141561240a57876001600160a01b031660006001600160a01b0316336001600160a01b0316600080516020613ba08339815191528489604051612401929190613830565b60405180910390a45b866001600160a01b0316886001600160a01b03167ff4d42fc7416f300569832aee6989201c613d31d64b823327915a6a33fe7afa558888886040516124519392919061383e565b60405180910390a35050505050505050565b6060600061246f610983565b60e48101549091508067ffffffffffffffff8111801561248e57600080fd5b506040519080825280602002602001820160405280156124b8578160200160208202803683370190505b50925060005b8181101561251b578260e40181815481106124d557fe5b60009182526020909120015484516001600160a01b03909116908590839081106124fb57fe5b6001600160a01b03909216602092830291909101909101526001016124be565b50505090565b60008061252c610983565b6001600160a01b038416600090815260398201602052604090205460038201549192506125a9916125749163ffffffff918216600b0b91600160601b909104811690612f5116565b6001600160a01b038516600090815260398401602052604090205463ffffffff600160201b9091048116600b0b91906126a916565b6001600160a01b03909316600090815260399091016020526040902054600160801b9004600b0b91909101919050565b600081600b0b60001415612634576040805162461bcd60e51b815260206004820181905260248201527f5369676e6564536166654d6174683a206469766973696f6e206279207a65726f604482015290519081900360640190fd5b81600b0b6000191480156126535750600b83900b60016001605f1b0319145b1561268f5760405162461bcd60e51b8152600401808060200182810382526021815260200180613c076021913960400191505060405180910390fd5b600082600b0b84600b0b816126a057fe5b05949350505050565b600082600b0b600014156126bf575060006112f3565b82600b0b6000191480156126de5750600b82900b60016001605f1b0319145b1561271a5760405162461bcd60e51b8152600401808060200182810382526027815260200180613c496027913960400191505060405180910390fd5b6000828402905082600b0b84600b0b82600b0b8161273457fe5b05600b0b146112f05760405162461bcd60e51b8152600401808060200182810382526027815260200180613c496027913960400191505060405180910390fd5b600061278b63ffffffff8084169060029061317f16565b63ffffffff161561279d5760016112f3565b600092915050565b60008060006127b2610983565b905083156127f5576001600160a01b03851660009081526031820160205260409020601c01546001600160801b038082169450600160801b90910416915061282a565b6001600160a01b03851660009081526031820160205260409020601c01546001600160801b03600160801b8204811694501691505b509250929050565b60008263ffffffff168263ffffffff16111561133e576040805162461bcd60e51b815260206004820152601e6024820152600080516020613c70833981519152604482015290519081900360640190fd5b6000806000612890610983565b905061289c86866131eb565b925083156128d6576001600160a01b03871660009081526031820160205260408120601c0180546001600160801b03191690559150612905565b6001600160a01b03871660009081526031820160205260409020601c0180546001600160801b03169055600191505b63ffffffff808716600090815260e383016020526040902054612936916001600160801b03909116908790612efa16565b63ffffffff878116600090815260e384016020526040902080546001600160801b0319166001600160801b03938416179081905561298092600160801b90910416908590612efa16565b63ffffffff909616600090815260e39091016020526040902080546001600160801b03968716600160801b02961695909517909455949293505050565b60008282016001600160801b0380851690821610156112f0576040805162461bcd60e51b815260206004820152601b60248201527a536166654d6174683a206164646974696f6e206f766572666c6f7760281b604482015290519081900360640190fd5b600080612a2c610983565b6001600160a01b038416600090815260318201602052604081206014810154600a82015490955092935091600160601b900463ffffffff1615612b5457600a820154600160401b810463ffffffff908116600160601b909204161415612a9757506013810154612abc565b50600a810154600160401b900463ffffffff166000908152603d830160205260409020545b6001600160a01b03851660009081526031840160209081526040808320600a0154600160601b900463ffffffff168352603d860190915290205481811115612b4e576001600160a01b03861660009081526031850160205260409020601201549091829190820390612b4a90612b439069d3c21bcecceda10000009061143090859061186c565b8790611298565b9550505b50612b90565b506001600160a01b03841660009081526031830160209081526040808320600a0154600160401b900463ffffffff168352603d85019091529020545b612b99856132a2565b600384015463ffffffff918216600160201b9091049091161115612c3657600383015463ffffffff600160201b90910481166000908152603d850160205260408120549091612beb919084906112f916565b6001600160a01b03871660009081526031860160205260409020600e0154909150612c3290612c2b9069d3c21bcecceda10000009061143090859061186c565b8690611298565b9450505b505050919050565b60006116b3848484611703565b60006112f082612c5a856132e1565b63ffffffff166133f8565b6000808211612cb6576040805162461bcd60e51b8152602060048201526018602482015277536166654d6174683a206d6f64756c6f206279207a65726f60401b604482015290519081900360640190fd5b818381612cbf57fe5b069392505050565b6000806000612cd4610983565b90506000612cf288612ced600b8a900b620f42406125d9565b61175c565b6001600160a01b038a16600090815260318401602090815260408083208484526019019091529020549091506001600160801b0380821691600160801b900416612d3c8883611298565b9750612d488782611298565b6001600160a01b038c166000818152603187016020908152604080832088845260190190915280822082905551929950913390600080516020613ba083398151915290612d989088908890613830565b60405180910390a46001600160a01b03808b16908c167f153f0425cb9f489d8ca1232a9a790fb1ee212c4d80bb8cf8c83b0f5b203bab1c612de0600b8d900b620f42406125d9565b8585604051612df19392919061383e565b60405180910390a36001600160a01b038b16600033600080516020613ba0833981519152612e1f8e8e61175c565b86604051612e2e929190613830565b60405180910390a4896001600160a01b03168b6001600160a01b03167ff4d42fc7416f300569832aee6989201c613d31d64b823327915a6a33fe7afa558b8585604051612e7d9392919061383e565b60405180910390a3509599949850939650505050505050565b6000808211612ee9576040805162461bcd60e51b815260206004820152601a602482015279536166654d6174683a206469766973696f6e206279207a65726f60301b604482015290519081900360640190fd5b818381612ef257fe5b049392505050565b6000826001600160801b0316826001600160801b0316111561133e576040805162461bcd60e51b815260206004820152601e6024820152600080516020613c70833981519152604482015290519081900360640190fd5b6000818303600b83900b8213801590612f70575083600b0b81600b0b13155b80612f8e5750600083600b0b128015612f8e575083600b0b81600b0b135b6112f05760405162461bcd60e51b8152600401808060200182810382526024815260200180613c906024913960400191505060405180910390fd5b60006001600160801b038316612fe1575060006112f3565b8282026001600160801b038084169080861690831681612ffd57fe5b046001600160801b0316146112f05760405162461bcd60e51b8152600401808060200182810382526021815260200180613c286021913960400191505060405180910390fd5b600080826001600160801b03161161309f576040805162461bcd60e51b815260206004820152601a602482015279536166654d6174683a206469766973696f6e206279207a65726f60301b604482015290519081900360640190fd5b816001600160801b0316836001600160801b031681612ef257fe5b60006b7fffffffffffffffffffffff8211156116ff5760405162461bcd60e51b815260040161007e906138c4565b60008160000151600b0b83600b0b1215613104575060026112f3565b8160200151600b0b83600b0b14156131335761311e6133fd565b61312957600161312c565b60005b90506112f3565b61313b6133fd565b61314657600061312c565b5060016112f3565b64e8d4a5100090565b600080613162610983565b60038101549091506131799063ffffffff1661341f565b91505090565b6000808263ffffffff16116131d6576040805162461bcd60e51b8152602060048201526018602482015277536166654d6174683a206d6f64756c6f206279207a65726f60401b604482015290519081900360640190fd5b8163ffffffff168363ffffffff1681612cbf57fe5b6000806131f6610983565b63ffffffff8516600090815260e3820160205260409020549091506001600160801b03848116911614156132535763ffffffff8416600090815260e382016020526040902054600160801b90046001600160801b0316915061329b565b63ffffffff808516600090815260e38301602052604090205461329891610956916001600160801b03808216926114309289831692600160801b909104169061186c16565b91505b5092915050565b6000806132ad610983565b6001600160a01b03939093166000908152603193909301602052505060409020600a0154600160201b900463ffffffff1690565b6000806132ec610983565b60038101546001600160a01b038516600090815260398301602052604090205491925063ffffffff908116600160601b909204161015613355576001600160a01b0383166000908152603982016020526040902054600160201b900463ffffffff1691506133f2565b6001600160a01b0383166000908152603982016020526040812054600160e81b9004600290810b919082900b126133bc576001600160a01b0384166000908152603983016020526040902054600282900b600160201b90910463ffffffff160392506133f0565b6001600160a01b038416600090815260398301602052604081205463ffffffff600160201b909104169082900360020b0192505b505b50919050565b900390565b600080613408610983565b60038101549091506131799063ffffffff16612774565b600061342a82612774565b61279d5760016112f3565b6040518060800160405280613448613486565b8152602001613455613486565b8152602001613462613486565b8152602001600081525090565b604080518082019091526000808252602082015290565b60405180606001604052806000815260200160008152602001600081525090565b80516001600160a01b0381168114610ada57600080fd5b600082601f8301126134ce578081fd5b813560206134e36134de83613b81565b613b5d565b82815281810190858301838502870184018810156134ff578586fd5b855b8581101561352b57813580600b0b8114613519578788fd5b84529284019290840190600101613501565b5090979650505050505050565b600082601f830112613548578081fd5b813560206135586134de83613b81565b8281528181019085830183850287018401881015613574578586fd5b855b8581101561352b57813584529284019290840190600101613576565b600080600080608085870312156135a7578384fd5b6135b0856134a7565b93506135be602086016134a7565b6040860151606090960151949790965092505050565b600080600080606085870312156135e9578384fd5b843567ffffffffffffffff80821115613600578586fd5b818701915087601f830112613613578586fd5b813581811115613621578687fd5b886020828501011115613632578687fd5b60209283019650945090860135908082111561364c578384fd5b613658888389016134be565b9350604087013591508082111561366d578283fd5b5061367a87828801613538565b91505092959194509250565b6000815180845260208085019450808401835b838110156136b557815187529582019590820190600101613699565b509495945050505050565b600381106136ca57fe5b9052565b60008251815b818110156136ee57602081860181015185830152016136d4565b818111156136fc5782828501525b509190910192915050565b6001600160a01b0394851681529290931660208301526040820152606081019190915260800190565b6001600160a01b03929092168252602082015260400190565b6080808252855190820181905260009060209060a0840190828901845b82811015613785578151600b0b84529284019290840190600101613766565b505050838103828501526137998188613686565b91505084604084015282810360608401526137b48185613686565b979650505050505050565b6000604082526137d26040830185613686565b82810360208401526137e48185613686565b95945050505050565b60006020825282602083015282846040840137818301604090810191909152601f909201601f19160101919050565b8281526040810161175560208301846136c0565b918252602082015260400190565b600b9390930b83526020830191909152604082015260600190565b600b9590950b8552602085019390935260408401919091526060830152608082015260a00190565b60208082526023908201527f436f6e766572743a204e6f7420656e6f75676820746f6b656e732072656d6f7660408201526232b21760e91b606082015260800190565b60208082526027908201527f53616665436173743a2076616c756520646f65736e27742066697420696e2061604082015266371034b73a1c9b60c91b606082015260800190565b602080825260179082015276696e76616c6964206765726d696e6174696f6e4d6f646560481b604082015260600190565b60208082526029908201527f436f6e766572743a207374656d732c20616d6f756e7473206172652064696666604082015268103632b733ba34399760b91b606082015260800190565b60208082526018908201527753696c6f3a20496e76616c696420656e636f64655479706560401b604082015260600190565b6020808252601c908201527f53696c6f3a2043726174652062616c616e636520746f6f206c6f772e00000000604082015260600190565b6020808252601a908201527f436f6e766572743a2046726f6d20616d6f756e7420697320302e000000000000604082015260600190565b6020808252601b908201527f53696c6f3a20546f6b656e206e6f742077686974656c69737465640000000000604082015260600190565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b60208082526016908201527514da5b1bce88135a59dc985d1a5bdb881b995959195960521b604082015260600190565b6020808252601c908201527f436f6e766572743a20424456206f7220616d6f756e7420697320302e00000000604082015260600190565b6001600160801b03831681526040810161175560208301846136c0565b90815260200190565b63ffffffff9390931683526020830191909152604082015260600190565b63ffffffff9290921682526001600160801b0316602082015260400190565b60405181810167ffffffffffffffff81118282101715613b7957fe5b604052919050565b600067ffffffffffffffff821115613b9557fe5b506020908102019056fec3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f6253616665436173743a2076616c756520646f65736e27742066697420696e2031323820626974739c0c70ad39ba6959d6008b9bc651f15ce23613cc1c5ebb4c6ffba0e53a1ea7055369676e6564536166654d6174683a206469766973696f6e206f766572666c6f77536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f775369676e6564536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77536166654d6174683a207375627472616374696f6e206f766572666c6f7700005369676e6564536166654d6174683a207375627472616374696f6e206f766572666c6f77b2d61db64b8ad7535308d2111c78934bc32baf9b7cd3a2e58cba25730003cd58a26469706673582212207cb26d79f6f9b939cd495e5abb7fcc24ed579cc2ac5235905d980941f7d51c2d64736f6c63430007060033
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 30 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
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.