{ "language": "Solidity", "sources": { "@openzeppelin/contracts/math/SafeMath.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the substraction of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b <= a, \"SafeMath: subtraction overflow\");\n return a - b;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a == 0) return 0;\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b > 0, \"SafeMath: division by zero\");\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b > 0, \"SafeMath: modulo by zero\");\n return a % b;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {trySub}.\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n return a - b;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryDiv}.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting with custom message when dividing by zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryMod}.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n return a % b;\n }\n}\n" }, "@openzeppelin/contracts/token/ERC20/IERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n" }, "@openzeppelin/contracts/utils/Counters.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../math/SafeMath.sol\";\n\n/**\n * @title Counters\n * @author Matt Condon (@shrugs)\n * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number\n * of elements in a mapping, issuing ERC721 ids, or counting request ids.\n *\n * Include with `using Counters for Counters.Counter;`\n * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}\n * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never\n * directly accessed.\n */\nlibrary Counters {\n using SafeMath for uint256;\n\n struct Counter {\n // This variable should never be directly accessed by users of the library: interactions must be restricted to\n // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add\n // this feature: see https://github.com/ethereum/solidity/issues/4637\n uint256 _value; // default: 0\n }\n\n function current(Counter storage counter) internal view returns (uint256) {\n return counter._value;\n }\n\n function increment(Counter storage counter) internal {\n // The {SafeMath} overflow check can be skipped here, see the comment at the top\n counter._value += 1;\n }\n\n function decrement(Counter storage counter) internal {\n counter._value = counter._value.sub(1);\n }\n}\n" }, "contracts/C.sol": { "content": "/*\n SPDX-License-Identifier: MIT\n*/\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport \"./interfaces/IBean.sol\";\nimport \"./interfaces/ICurve.sol\";\nimport \"./interfaces/IFertilizer.sol\";\nimport \"./interfaces/IProxyAdmin.sol\";\nimport \"./libraries/Decimal.sol\";\n\n/**\n * @author Publius\n * @title C holds the contracts for Beanstalk.\n**/\nlibrary C {\n\n using Decimal for Decimal.D256;\n using SafeMath for uint256;\n\n // Constants\n uint256 private constant PERCENT_BASE = 1e18;\n uint256 private constant PRECISION = 1e18;\n\n // Chain\n uint256 private constant CHAIN_ID = 1; // Mainnet\n\n // Season\n uint256 private constant CURRENT_SEASON_PERIOD = 3600; // 1 hour\n uint256 private constant BASE_ADVANCE_INCENTIVE = 25e6; // 25 beans\n uint256 private constant SOP_PRECISION = 1e24;\n\n // Sun\n uint256 private constant FERTILIZER_DENOMINATOR = 3;\n uint256 private constant HARVEST_DENOMINATOR = 2;\n uint256 private constant SOIL_COEFFICIENT_HIGH = 0.5e18;\n uint256 private constant SOIL_COEFFICIENT_LOW = 1.5e18;\n\n // Weather\n uint256 private constant POD_RATE_LOWER_BOUND = 0.05e18; // 5%\n uint256 private constant OPTIMAL_POD_RATE = 0.15e18; // 15%\n uint256 private constant POD_RATE_UPPER_BOUND = 0.25e18; // 25%\n uint32 private constant STEADY_SOW_TIME = 60; // 1 minute\n\n uint256 private constant DELTA_POD_DEMAND_LOWER_BOUND = 0.95e18; // 95%\n uint256 private constant DELTA_POD_DEMAND_UPPER_BOUND = 1.05e18; // 105%\n\n // Silo\n uint256 private constant SEEDS_PER_BEAN = 2;\n uint256 private constant STALK_PER_BEAN = 10000;\n uint256 private constant ROOTS_BASE = 1e12;\n\n\n // Exploit\n uint256 private constant UNRIPE_LP_PER_DOLLAR = 1884592; // 145_113_507_403_282 / 77_000_000\n uint256 private constant ADD_LP_RATIO = 866616;\n uint256 private constant INITIAL_HAIRCUT = 185564685220298701; // SET\n\n // Contracts\n address private constant BEAN = 0xBEA0000029AD1c77D3d5D23Ba2D8893dB9d1Efab;\n address private constant CURVE_BEAN_METAPOOL = 0xc9C32cd16Bf7eFB85Ff14e0c8603cc90F6F2eE49;\n address private constant CURVE_3_POOL = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;\n address private constant THREE_CRV = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;\n address private constant UNRIPE_BEAN = 0x1BEA0050E63e05FBb5D8BA2f10cf5800B6224449;\n address private constant UNRIPE_LP = 0x1BEA3CcD22F4EBd3d37d731BA31Eeca95713716D;\n address private constant FERTILIZER = 0x402c84De2Ce49aF88f5e2eF3710ff89bFED36cB6;\n address private constant FERTILIZER_ADMIN = 0xfECB01359263C12Aa9eD838F878A596F0064aa6e;\n address private constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;\n\n address private constant TRI_CRYPTO = 0xc4AD29ba4B3c580e6D59105FFf484999997675Ff;\n address private constant TRI_CRYPTO_POOL = 0xD51a44d3FaE010294C616388b506AcdA1bfAAE46;\n address private constant CURVE_ZAP = 0xA79828DF1850E8a3A3064576f380D90aECDD3359;\n\n address private constant UNRIPE_CURVE_BEAN_LUSD_POOL = 0xD652c40fBb3f06d6B58Cb9aa9CFF063eE63d465D;\n address private constant UNRIPE_CURVE_BEAN_METAPOOL = 0x3a70DfA7d2262988064A2D051dd47521E43c9BdD;\n\n /**\n * Getters\n **/\n\n function getSeasonPeriod() internal pure returns (uint256) {\n return CURRENT_SEASON_PERIOD;\n }\n\n function getAdvanceIncentive() internal pure returns (uint256) {\n return BASE_ADVANCE_INCENTIVE;\n }\n\n function getFertilizerDenominator() internal pure returns (uint256) {\n return FERTILIZER_DENOMINATOR;\n }\n\n function getHarvestDenominator() internal pure returns (uint256) {\n return HARVEST_DENOMINATOR;\n }\n\n function getChainId() internal pure returns (uint256) {\n return CHAIN_ID;\n }\n\n function getOptimalPodRate() internal pure returns (Decimal.D256 memory) {\n return Decimal.ratio(OPTIMAL_POD_RATE, PERCENT_BASE);\n }\n\n function getUpperBoundPodRate() internal pure returns (Decimal.D256 memory) {\n return Decimal.ratio(POD_RATE_UPPER_BOUND, PERCENT_BASE);\n }\n\n function getLowerBoundPodRate() internal pure returns (Decimal.D256 memory) {\n return Decimal.ratio(POD_RATE_LOWER_BOUND, PERCENT_BASE);\n }\n\n function getUpperBoundDPD() internal pure returns (Decimal.D256 memory) {\n return Decimal.ratio(DELTA_POD_DEMAND_UPPER_BOUND, PERCENT_BASE);\n }\n\n function getLowerBoundDPD() internal pure returns (Decimal.D256 memory) {\n return Decimal.ratio(DELTA_POD_DEMAND_LOWER_BOUND, PERCENT_BASE);\n }\n\n function getSteadySowTime() internal pure returns (uint32) {\n return STEADY_SOW_TIME;\n }\n\n function getSeedsPerBean() internal pure returns (uint256) {\n return SEEDS_PER_BEAN;\n }\n\n function getStalkPerBean() internal pure returns (uint256) {\n return STALK_PER_BEAN;\n }\n\n function getRootsBase() internal pure returns (uint256) {\n return ROOTS_BASE;\n }\n\n function getSopPrecision() internal pure returns (uint256) {\n return SOP_PRECISION;\n }\n\n function beanAddress() internal pure returns (address) {\n return BEAN;\n }\n\n function curveMetapoolAddress() internal pure returns (address) {\n return CURVE_BEAN_METAPOOL;\n }\n\n function unripeLPPool1() internal pure returns (address) {\n return UNRIPE_CURVE_BEAN_METAPOOL;\n }\n\n function unripeLPPool2() internal pure returns (address) {\n return UNRIPE_CURVE_BEAN_LUSD_POOL;\n }\n\n function unripeBeanAddress() internal pure returns (address) {\n return UNRIPE_BEAN;\n }\n\n function unripeLPAddress() internal pure returns (address) {\n return UNRIPE_LP;\n }\n\n function unripeBean() internal pure returns (IERC20) {\n return IERC20(UNRIPE_BEAN);\n }\n\n function unripeLP() internal pure returns (IERC20) {\n return IERC20(UNRIPE_LP);\n }\n\n function bean() internal pure returns (IBean) {\n return IBean(BEAN);\n }\n\n function usdc() internal pure returns (IERC20) {\n return IERC20(USDC);\n }\n\n function curveMetapool() internal pure returns (ICurvePool) {\n return ICurvePool(CURVE_BEAN_METAPOOL);\n }\n\n function curve3Pool() internal pure returns (I3Curve) {\n return I3Curve(CURVE_3_POOL);\n }\n \n function curveZap() internal pure returns (ICurveZap) {\n return ICurveZap(CURVE_ZAP);\n }\n\n function curveZapAddress() internal pure returns (address) {\n return CURVE_ZAP;\n }\n\n function curve3PoolAddress() internal pure returns (address) {\n return CURVE_3_POOL;\n }\n\n function threeCrv() internal pure returns (IERC20) {\n return IERC20(THREE_CRV);\n }\n\n function fertilizer() internal pure returns (IFertilizer) {\n return IFertilizer(FERTILIZER);\n }\n\n function fertilizerAddress() internal pure returns (address) {\n return FERTILIZER;\n }\n\n function fertilizerAdmin() internal pure returns (IProxyAdmin) {\n return IProxyAdmin(FERTILIZER_ADMIN);\n }\n\n function triCryptoPoolAddress() internal pure returns (address) {\n return TRI_CRYPTO_POOL;\n }\n\n function triCrypto() internal pure returns (IERC20) {\n return IERC20(TRI_CRYPTO);\n }\n\n function unripeLPPerDollar() internal pure returns (uint256) {\n return UNRIPE_LP_PER_DOLLAR;\n }\n\n function dollarPerUnripeLP() internal pure returns (uint256) {\n return 1e12/UNRIPE_LP_PER_DOLLAR;\n }\n\n function exploitAddLPRatio() internal pure returns (uint256) {\n return ADD_LP_RATIO;\n }\n\n function precision() internal pure returns (uint256) {\n return PRECISION;\n }\n\n function initialRecap() internal pure returns (uint256) {\n return INITIAL_HAIRCUT;\n }\n\n function soilCoefficientHigh() internal pure returns (uint256) {\n return SOIL_COEFFICIENT_HIGH;\n }\n\n function soilCoefficientLow() internal pure returns (uint256) {\n return SOIL_COEFFICIENT_LOW;\n }\n}\n" }, "contracts/farm/AppStorage.sol": { "content": "/*\n SPDX-License-Identifier: MIT\n*/\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport \"../interfaces/IDiamondCut.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/utils/Counters.sol\";\n\n/**\n * @author Publius\n * @title App Storage defines the state object for Beanstalk.\n**/\n\n// The Account contract stores all of the Farmer specific storage data.\n// Each unique Ethereum address is a Farmer.\n// Account.State is the primary struct that is referenced in the greater Storage.State struct.\n// All other structs in Account are stored in Account.State.\ncontract Account {\n\n // Field stores a Farmer's Plots and Pod allowances.\n struct Field {\n mapping(uint256 => uint256) plots; // A Farmer's Plots. Maps from Plot index to Pod amount.\n mapping(address => uint256) podAllowances; // An allowance mapping for Pods similar to that of the ERC-20 standard. Maps from spender address to allowance amount.\n }\n\n // Asset Silo is a struct that stores Deposits and Seeds per Deposit, and formerly stored Withdrawals.\n // Asset Silo currently stores Unripe Bean and Unripe LP Deposits.\n struct AssetSilo {\n mapping(uint32 => uint256) withdrawals; // DEPRECATED – Silo V1 Withdrawals are no longer referenced.\n mapping(uint32 => uint256) deposits; // Unripe Bean/LP Deposits (previously Bean/LP Deposits).\n mapping(uint32 => uint256) depositSeeds; // BDV of Unripe LP Deposits / 4 (previously # of Seeds in corresponding LP Deposit).\n }\n\n // Deposit represents a Deposit in the Silo of a given Token at a given Season.\n // Stored as two uint128 state variables to save gas.\n struct Deposit {\n uint128 amount; // The amount of Tokens in the Deposit.\n uint128 bdv; // The Bean-denominated-value of the total amount of Tokens in the Deposit.\n }\n\n // Silo stores Silo-related balances\n struct Silo {\n uint256 stalk; // Balance of the Farmer's normal Stalk.\n uint256 seeds; // Balance of the Farmer's normal Seeds.\n }\n\n // Season Of Plenty stores Season of Plenty (SOP) related balances\n struct SeasonOfPlenty {\n // uint256 base; // DEPRECATED – Post Replant SOPs are denominated in plenty Tokens instead of base.\n uint256 roots; // The number of Roots a Farmer had when it started Raining.\n // uint256 basePerRoot; // DEPRECATED – Post Replant SOPs are denominated in plenty Tokens instead of base.\n uint256 plentyPerRoot; // The global Plenty Per Root index at the last time a Farmer updated their Silo. \n uint256 plenty; // The balance of a Farmer's plenty. Plenty can be claimed directly for 3Crv.\n }\n\n // The Account level State stores all of the Farmer's balances in the contract.\n // The global AppStorage state stores a mapping from account address to Account.State.\n struct State {\n Field field; // A Farmer's Field storage.\n AssetSilo bean; // A Farmer's Unripe Bean Deposits only as a result of Replant (previously held the V1 Silo Deposits/Withdrawals for Beans).\n AssetSilo lp; // A Farmer's Unripe LP Deposits as a result of Replant of BEAN:ETH Uniswap v2 LP Tokens (previously held the V1 Silo Deposits/Withdrawals for BEAN:ETH Uniswap v2 LP Tokens).\n Silo s; // A Farmer's Silo storage.\n uint32 votedUntil; // DEPRECATED – Replant removed on-chain governance including the ability to vote on BIPs.\n uint32 lastUpdate; // The Season in which the Farmer last updated their Silo.\n uint32 lastSop; // The last Season that a SOP occured at the time the Farmer last updated their Silo.\n uint32 lastRain; // The last Season that it started Raining at the time the Farmer last updated their Silo.\n uint32 lastSIs; // DEPRECATED – In Silo V1.2, the Silo reward mechanism was updated to no longer need to store the number of the Supply Increases at the time the Farmer last updated their Silo.\n uint32 proposedUntil; // DEPRECATED – Replant removed on-chain governance including the ability to propose BIPs.\n SeasonOfPlenty deprecated; // DEPRECATED – Replant reset the Season of Plenty mechanism\n uint256 roots; // A Farmer's Root balance.\n uint256 wrappedBeans; // DEPRECATED – Replant generalized Internal Balances. Wrapped Beans are now stored at the AppStorage level.\n mapping(address => mapping(uint32 => Deposit)) deposits; // A Farmer's Silo Deposits stored as a map from Token address to Season of Deposit to Deposit.\n mapping(address => mapping(uint32 => uint256)) withdrawals; // A Farmer's Withdrawals from the Silo stored as a map from Token address to Season the Withdrawal becomes Claimable to Withdrawn amount of Tokens.\n SeasonOfPlenty sop; // A Farmer's Season Of Plenty storage.\n mapping(address => mapping(address => uint256)) depositAllowances; // Spender => Silo Token\n mapping(address => mapping(IERC20 => uint256)) tokenAllowances; // Token allowances\n uint256 depositPermitNonces; // A Farmer's current deposit permit nonce\n uint256 tokenPermitNonces; // A Farmer's current token permit nonce\n }\n}\n\n// Storage stores the Global Beanstalk State.\n// Storage.State stores the highest level State\n// All Facets define Storage.State as the first and only state variable in the contract.\ncontract Storage {\n\n // DEPRECATED – After Replant, Beanstalk stores Token addresses as constants to save gas.\n // Contracts stored the contract addresses of various important contracts to Beanstalk.\n struct Contracts {\n address bean; // DEPRECATED – See above note\n address pair; // DEPRECATED – See above note\n address pegPair; // DEPRECATED – See above note\n address weth; // DEPRECATED – See above note\n }\n\n // Field stores global Field balances.\n struct Field {\n uint256 soil; // The number of Soil currently available.\n uint256 pods; // The pod index; the total number of Pods ever minted.\n uint256 harvested; // The harvested index; the total number of Pods that have ever been Harvested.\n uint256 harvestable; // The harvestable index; the total number of Pods that have ever been Harvestable. Included previously Harvested Beans.\n }\n\n // DEPRECATED – Replant moved governance off-chain.\n // Bip stores Bip related data.\n struct Bip {\n address proposer; // DEPRECATED – See above note\n uint32 start; // DEPRECATED – See above note\n uint32 period; // DEPRECATED – See above note\n bool executed; // DEPRECATED – See above note\n int pauseOrUnpause; // DEPRECATED – See above note\n uint128 timestamp; // DEPRECATED – See above note\n uint256 roots; // DEPRECATED – See above note\n uint256 endTotalRoots; // DEPRECATED – See above note\n }\n\n // DEPRECATED – Replant moved governance off-chain.\n // DiamondCut stores DiamondCut related data for each Bip.\n struct DiamondCut {\n IDiamondCut.FacetCut[] diamondCut;\n address initAddress;\n bytes initData;\n }\n\n // DEPRECATED – Replant moved governance off-chain.\n // Governance stores global Governance balances.\n struct Governance {\n uint32[] activeBips; // DEPRECATED – See above note\n uint32 bipIndex; // DEPRECATED – See above note\n mapping(uint32 => DiamondCut) diamondCuts; // DEPRECATED – See above note\n mapping(uint32 => mapping(address => bool)) voted; // DEPRECATED – See above note\n mapping(uint32 => Bip) bips; // DEPRECATED – See above note\n }\n\n // AssetSilo stores global Token level Silo balances.\n // In Storage.State there is a mapping from Token address to AssetSilo.\n struct AssetSilo {\n uint256 deposited; // The total number of a given Token currently Deposited in the Silo.\n uint256 withdrawn; // The total number of a given Token currently Withdrawn From the Silo but not Claimed.\n }\n\n // Silo stores global level Silo balances.\n struct Silo {\n uint256 stalk; // The total amount of active Stalk (including Earned Stalk, excluding Grown Stalk).\n uint256 seeds; // The total amount of active Seeds (excluding Earned Seeds).\n uint256 roots; // Total amount of Roots.\n }\n\n // Oracle stores global level Oracle balances.\n // Currently the oracle refers to the time weighted average delta b calculated from the Bean:3Crv pool.\n struct Oracle {\n bool initialized; // True if the Oracle has been initialzed. It needs to be initialized on Deployment and re-initialized each Unpause.\n uint32 startSeason; // The Season the Oracle started minting. Used to ramp up delta b when oracle is first added.\n uint256[2] balances; // The cumulative reserve balances of the pool at the start of the Season (used for computing time weighted average delta b).\n uint256 timestamp; // The timestamp of the start of the current Season.\n }\n\n // Rain stores global level Rain balances. (Rain is when P > 1, Pod rate Excessively Low).\n // Note: The `raining` storage variable is stored in the Season section for a gas efficient read operation.\n struct Rain {\n uint256 depreciated; // Ocupies a storage slot in place of a deprecated State variable.\n uint256 pods; // The number of Pods when it last started Raining.\n uint256 roots; // The number of Roots when it last started Raining.\n }\n\n // Sesaon stores global level Season balances.\n struct Season {\n // The first storage slot in Season is filled with a variety of somewhat unrelated storage variables.\n // Given that they are all smaller numbers, they are stored together for gas efficient read/write operations. \n // Apologies if this makes it confusing :(\n uint32 current; // The current Season in Beanstalk.\n uint32 lastSop; // The Season in which the most recent consecutive series of Seasons of Plenty started.\n uint8 withdrawSeasons; // The number of seasons required to Withdraw a Deposit.\n uint32 lastSopSeason; // The Season in which the most recent consecutive series of Seasons of Plenty ended.\n uint32 rainStart; // rainStart stores the most recent Season in which Rain started.\n bool raining; // True if it is Raining (P < 1, Pod Rate Excessively Low).\n bool fertilizing; // True if Beanstalk has Fertilizer left to be paid off.\n uint256 start; // The timestamp of the Beanstalk deployment rounded down to the nearest hour.\n uint256 period; // The length of each season in Beanstalk.\n uint256 timestamp; // The timestamp of the start of the current Season.\n }\n\n // Weather stores global level Weather balances.\n struct Weather {\n uint256 startSoil; // The number of Soil at the start of the current Season.\n uint256 lastDSoil; // Delta Soil; the number of Soil purchased last Season.\n uint96 lastSoilPercent; // DEPRECATED: Was removed with Extreme Weather V2\n uint32 lastSowTime; // The number of seconds it took for all but at most 1 Soil to sell out last Season.\n uint32 nextSowTime; // The number of seconds it took for all but at most 1 Soil to sell out this Season\n uint32 yield; // Weather; the interest rate for sowing Beans in Soil.\n bool didSowBelowMin; // DEPRECATED: Was removed with Extreme Weather V2\n bool didSowFaster; // DEPRECATED: Was removed with Extreme Weather V2\n }\n\n // Fundraiser stores Fundraiser data for a given Fundraiser.\n struct Fundraiser {\n address payee; // The address to be paid after the Fundraiser has been fully funded.\n address token; // The token address that used to raise funds for the Fundraiser.\n uint256 total; // The total number of Tokens that need to be raised to complete the Fundraiser.\n uint256 remaining; // The remaining number of Tokens that need to to complete the Fundraiser.\n uint256 start; // The timestamp at which the Fundraiser started (Fundraisers cannot be started and funded in the same block).\n }\n\n // SiloSettings stores the settings for each Token that has been Whitelisted into the Silo.\n // A Token is considered whitelisted in the Silo if there exists a non-zero SiloSettings selector.\n struct SiloSettings {\n // selector is an encoded function selector \n // that pertains to an external view Beanstalk function \n // with the following signature:\n // function tokenToBdv(uint256 amount) public view returns (uint256);\n // It is called by `LibTokenSilo` through the use of delegatecall\n // To calculate the BDV of a Deposit at the time of Deposit.\n bytes4 selector; // The encoded BDV function selector for the Token.\n uint32 seeds; // The Seeds Per BDV that the Silo mints in exchange for Depositing this Token.\n uint32 stalk; // The Stalk Per BDV that the Silo mints in exchange for Depositing this Token.\n }\n\n // UnripeSettings stores the settings for an Unripe Token in Beanstalk.\n // An Unripe token is a vesting Token that is redeemable for a a pro rata share\n // of the balanceOfUnderlying subject to a penalty based on the percent of\n // Unfertilized Beans paid back.\n // There were two Unripe Tokens added at Replant: \n // Unripe Bean with its underlying Token as Bean; and\n // Unripe LP with its underlying Token as Bean:3Crv LP.\n // Unripe Tokens are distirbuted through the use of a merkleRoot.\n // The existence of a non-zero UnripeSettings implies that a Token is an Unripe Token.\n struct UnripeSettings {\n address underlyingToken; // The address of the Token underlying the Unripe Token.\n uint256 balanceOfUnderlying; // The number of Tokens underlying the Unripe Tokens (redemption pool).\n bytes32 merkleRoot; // The Merkle Root used to validate a claim of Unripe Tokens.\n }\n}\n\nstruct AppStorage {\n uint8 index; // DEPRECATED - Was the index of the Bean token in the Bean:Eth Uniswap v2 pool, which has been depreciated.\n int8[32] cases; // The 24 Weather cases (array has 32 items, but caseId = 3 (mod 4) are not cases).\n bool paused; // True if Beanstalk is Paused.\n uint128 pausedAt; // The timestamp at which Beanstalk was last paused. \n Storage.Season season; // The Season storage struct found above.\n Storage.Contracts c; // DEPRECATED - Previously stored the Contracts State struct. Removed when contract addresses were moved to constants in C.sol.\n Storage.Field f; // The Field storage struct found above.\n Storage.Governance g; // The Governance storage struct found above.\n Storage.Oracle co; // The Oracle storage struct found above.\n Storage.Rain r; // The Rain storage struct found above.\n Storage.Silo s; // The Silo storage struct found above.\n uint256 reentrantStatus; // An intra-transaction state variable to protect against reentrance.\n Storage.Weather w; // The Weather storage struct found above.\n\n //////////////////////////////////\n\n uint256 earnedBeans; // The number of Beans distributed to the Silo that have not yet been Deposited as a result of the Earn function being called.\n uint256[14] depreciated; // DEPRECATED - 14 slots that used to store state variables which have been deprecated through various updates. Storage slots can be left alone or reused.\n mapping (address => Account.State) a; // A mapping from Farmer address to Account state.\n uint32 bip0Start; // DEPRECATED - bip0Start was used to aid in a migration that occured alongside BIP-0.\n uint32 hotFix3Start; // DEPRECATED - hotFix3Start was used to aid in a migration that occured alongside HOTFIX-3.\n mapping (uint32 => Storage.Fundraiser) fundraisers; // A mapping from Fundraiser Id to Fundraiser storage.\n uint32 fundraiserIndex; // The number of Fundraisers that have occured.\n mapping (address => bool) isBudget; // DEPRECATED - Budget Facet was removed in BIP-14. \n mapping(uint256 => bytes32) podListings; // A mapping from Plot Index to the hash of the Pod Listing.\n mapping(bytes32 => uint256) podOrders; // A mapping from the hash of a Pod Order to the amount of Pods that the Pod Order is still willing to buy.\n mapping(address => Storage.AssetSilo) siloBalances; // A mapping from Token address to Silo Balance storage (amount deposited and withdrawn).\n mapping(address => Storage.SiloSettings) ss; // A mapping from Token address to Silo Settings for each Whitelisted Token. If a non-zero storage exists, a Token is whitelisted.\n uint256[3] depreciated2; // DEPRECATED - 3 slots that used to store state variables which have been depreciated through various updates. Storage slots can be left alone or reused.\n\n // New Sops\n mapping (uint32 => uint256) sops; // A mapping from Season to Plenty Per Root (PPR) in that Season. Plenty Per Root is 0 if a Season of Plenty did not occur.\n\n // Internal Balances\n mapping(address => mapping(IERC20 => uint256)) internalTokenBalance; // A mapping from Farmer address to Token address to Internal Balance. It stores the amount of the Token that the Farmer has stored as an Internal Balance in Beanstalk.\n\n // Unripe\n mapping(address => mapping(address => bool)) unripeClaimed; // True if a Farmer has Claimed an Unripe Token. A mapping from Farmer to Unripe Token to its Claim status.\n mapping(address => Storage.UnripeSettings) u; // Unripe Settings for a given Token address. The existence of a non-zero Unripe Settings implies that the token is an Unripe Token. The mapping is from Token address to Unripe Settings.\n\n // Fertilizer\n mapping(uint128 => uint256) fertilizer; // A mapping from Fertilizer Id to the supply of Fertilizer for each Id.\n mapping(uint128 => uint128) nextFid; // A linked list of Fertilizer Ids ordered by Id number. Fertilizer Id is the Beans Per Fertilzer level at which the Fertilizer no longer receives Beans. Sort in order by which Fertilizer Id expires next.\n uint256 activeFertilizer; // The number of active Fertilizer.\n uint256 fertilizedIndex; // The total number of Fertilizer Beans.\n uint256 unfertilizedIndex; // The total number of Unfertilized Beans ever.\n uint128 fFirst; // The lowest active Fertilizer Id (start of linked list that is stored by nextFid). \n uint128 fLast; // The highest active Fertilizer Id (end of linked list that is stored by nextFid). \n uint128 bpf; // The cumulative Beans Per Fertilizer (bfp) minted over all Season.\n uint256 recapitalized; // The nubmer of USDC that has been recapitalized in the Barn Raise.\n uint256 isFarm; // Stores whether the function is wrapped in the `farm` function (1 if not, 2 if it is).\n address ownerCandidate; // Stores a candidate address to transfer ownership to. The owner must claim the ownership transfer.\n}" }, "contracts/farm/facets/WhitelistFacet.sol": { "content": "/**\n * SPDX-License-Identifier: MIT\n **/\n\npragma solidity ^0.7.6;\npragma experimental ABIEncoderV2;\n\nimport '../../seraph/SeraphProtected.sol';\nimport {LibDiamond} from \"../../libraries/LibDiamond.sol\";\nimport {LibWhitelist} from \"../../libraries/Silo/LibWhitelist.sol\";\nimport {AppStorage} from \"../AppStorage.sol\";\n\n/**\n * @author Publius\n * @title Whitelist Facet handles the whitelisting/dewhitelisting of assets.\n **/\ncontract WhitelistFacet is SeraphProtected {\n event WhitelistToken(\n address indexed token,\n bytes4 selector,\n uint256 seeds,\n uint256 stalk\n );\n\n event DewhitelistToken(address indexed token);\n\n function dewhitelistToken(address token) external payable withSeraphPayable {\n LibDiamond.enforceIsOwnerOrContract();\n LibWhitelist.dewhitelistToken(token);\n }\n\n function whitelistToken(\n address token,\n bytes4 selector,\n uint32 stalk,\n uint32 seeds\n ) external payable withSeraphPayable {\n LibDiamond.enforceIsOwnerOrContract();\n LibWhitelist.whitelistToken(\n token,\n selector,\n stalk,\n seeds\n );\n }\n}\n" }, "contracts/interfaces/IBean.sol": { "content": "/**\n * SPDX-License-Identifier: MIT\n**/\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n/**\n * @author Publius\n * @title Bean Interface\n**/\nabstract contract IBean is IERC20 {\n\n function burn(uint256 amount) public virtual;\n function burnFrom(address account, uint256 amount) public virtual;\n function mint(address account, uint256 amount) public virtual;\n\n}\n" }, "contracts/interfaces/ICurve.sol": { "content": "// SPDX-License-Identifier: MIT\npragma experimental ABIEncoderV2;\npragma solidity =0.7.6;\n\ninterface ICurvePool {\n function A_precise() external view returns (uint256);\n function get_balances() external view returns (uint256[2] memory);\n function totalSupply() external view returns (uint256);\n function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external returns (uint256);\n function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount) external returns (uint256);\n function balances(int128 i) external view returns (uint256);\n function fee() external view returns (uint256);\n function coins(uint256 i) external view returns (address);\n function get_virtual_price() external view returns (uint256);\n function calc_token_amount(uint256[2] calldata amounts, bool deposit) external view returns (uint256);\n function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);\n function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256);\n function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256);\n function transfer(address recipient, uint256 amount) external returns (bool);\n}\n\ninterface ICurveZap {\n function add_liquidity(address _pool, uint256[4] memory _deposit_amounts, uint256 _min_mint_amount) external returns (uint256);\n function calc_token_amount(address _pool, uint256[4] memory _amounts, bool _is_deposit) external returns (uint256);\n}\n\ninterface ICurvePoolR {\n function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);\n function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);\n function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount, address receiver) external returns (uint256);\n}\n\ninterface ICurvePool2R {\n function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount, address reciever) external returns (uint256);\n function remove_liquidity(uint256 _burn_amount, uint256[2] memory _min_amounts, address reciever) external returns (uint256[2] calldata);\n function remove_liquidity_imbalance(uint256[2] memory _amounts, uint256 _max_burn_amount, address reciever) external returns (uint256);\n}\n\ninterface ICurvePool3R {\n function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount, address reciever) external returns (uint256);\n function remove_liquidity(uint256 _burn_amount, uint256[3] memory _min_amounts, address reciever) external returns (uint256[3] calldata);\n function remove_liquidity_imbalance(uint256[3] memory _amounts, uint256 _max_burn_amount, address reciever) external returns (uint256);\n}\n\ninterface ICurvePool4R {\n function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount, address reciever) external returns (uint256);\n function remove_liquidity(uint256 _burn_amount, uint256[4] memory _min_amounts, address reciever) external returns (uint256[4] calldata);\n function remove_liquidity_imbalance(uint256[4] memory _amounts, uint256 _max_burn_amount, address reciever) external returns (uint256);\n}\n\ninterface I3Curve {\n function get_virtual_price() external view returns (uint256);\n}\n\ninterface ICurveFactory {\n function get_coins(address _pool) external view returns (address[4] calldata);\n function get_underlying_coins(address _pool) external view returns (address[8] calldata);\n}\n\ninterface ICurveCryptoFactory {\n function get_coins(address _pool) external view returns (address[8] calldata);\n}\n\ninterface ICurvePoolC {\n function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external returns (uint256);\n}\n\ninterface ICurvePoolNoReturn {\n function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external;\n function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external;\n function remove_liquidity(uint256 _burn_amount, uint256[3] memory _min_amounts) external;\n function remove_liquidity_imbalance(uint256[3] memory _amounts, uint256 _max_burn_amount) external;\n function remove_liquidity_one_coin(uint256 _token_amount, uint256 i, uint256 min_amount) external;\n}\n\ninterface ICurvePoolNoReturn128 {\n function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external;\n function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount) external;\n}\n" }, "contracts/interfaces/IDiamondCut.sol": { "content": "// SPDX-License-Identifier: MIT\npragma experimental ABIEncoderV2;\npragma solidity =0.7.6;\n/******************************************************************************\\\n* Author: Nick Mudge (https://twitter.com/mudgen)\n/******************************************************************************/\n\ninterface IDiamondCut {\n enum FacetCutAction {Add, Replace, Remove}\n\n struct FacetCut {\n address facetAddress;\n FacetCutAction action;\n bytes4[] functionSelectors;\n }\n\n /// @notice Add/replace/remove any number of functions and optionally execute\n /// a function with delegatecall\n /// @param _diamondCut Contains the facet addresses and function selectors\n /// @param _init The address of the contract or facet to execute _calldata\n /// @param _calldata A function call, including function selector and arguments\n /// _calldata is executed with delegatecall on _init\n function diamondCut(\n FacetCut[] calldata _diamondCut,\n address _init,\n bytes calldata _calldata\n ) external;\n\n event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);\n}\n" }, "contracts/interfaces/IDiamondLoupe.sol": { "content": "// SPDX-License-Identifier: MIT\npragma experimental ABIEncoderV2;\npragma solidity =0.7.6;\n// A loupe is a small magnifying glass used to look at diamonds.\n// These functions look at diamonds\ninterface IDiamondLoupe {\n /// These functions are expected to be called frequently\n /// by tools.\n\n struct Facet {\n address facetAddress;\n bytes4[] functionSelectors;\n }\n\n /// @notice Gets all facet addresses and their four byte function selectors.\n /// @return facets_ Facet\n function facets() external view returns (Facet[] memory facets_);\n\n /// @notice Gets all the function selectors supported by a specific facet.\n /// @param _facet The facet address.\n /// @return facetFunctionSelectors_\n function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_);\n\n /// @notice Get all the facet addresses used by a diamond.\n /// @return facetAddresses_\n function facetAddresses() external view returns (address[] memory facetAddresses_);\n\n /// @notice Gets the facet that supports the given selector.\n /// @dev If facet is not found return address(0).\n /// @param _functionSelector The function selector.\n /// @return facetAddress_ The facet address.\n function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_);\n}\n" }, "contracts/interfaces/IERC165.sol": { "content": "// SPDX-License-Identifier: MIT\npragma experimental ABIEncoderV2;\npragma solidity =0.7.6;\ninterface IERC165 {\n /// @notice Query if a contract implements an interface\n /// @param interfaceId The interface identifier, as specified in ERC-165\n /// @dev Interface identification is specified in ERC-165. This function\n /// uses less than 30,000 gas.\n /// @return `true` if the contract implements `interfaceID` and\n /// `interfaceID` is not 0xffffffff, `false` otherwise\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" }, "contracts/interfaces/IFertilizer.sol": { "content": "// SPDX-License-Identifier: MIT\npragma experimental ABIEncoderV2;\npragma solidity =0.7.6;\n\ninterface IFertilizer {\n struct Balance {\n uint128 amount;\n uint128 lastBpf;\n }\n function beanstalkUpdate(\n address account,\n uint256[] memory ids,\n uint128 bpf\n ) external returns (uint256);\n function beanstalkMint(address account, uint256 id, uint128 amount, uint128 bpf) external;\n function balanceOfFertilized(address account, uint256[] memory ids) external view returns (uint256);\n function balanceOfUnfertilized(address account, uint256[] memory ids) external view returns (uint256);\n function lastBalanceOf(address account, uint256 id) external view returns (Balance memory);\n function lastBalanceOfBatch(address[] memory account, uint256[] memory id) external view returns (Balance[] memory);\n function setURI(string calldata newuri) external;\n}" }, "contracts/interfaces/IProxyAdmin.sol": { "content": "// SPDX-License-Identifier: MIT\npragma experimental ABIEncoderV2;\npragma solidity =0.7.6;\ninterface IProxyAdmin {\n function upgrade(address proxy, address implementation) external;\n}\n" }, "contracts/libraries/Decimal.sol": { "content": "/*\n SPDX-License-Identifier: MIT\n*/\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport { SafeMath } from \"@openzeppelin/contracts/math/SafeMath.sol\";\n\n/**\n * @title Decimal\n * @author dYdX\n *\n * Library that defines a fixed-point number with 18 decimal places.\n */\nlibrary Decimal {\n using SafeMath for uint256;\n\n // ============ Constants ============\n\n uint256 constant BASE = 10**18;\n\n // ============ Structs ============\n\n\n struct D256 {\n uint256 value;\n }\n\n // ============ Static Functions ============\n\n function zero()\n internal\n pure\n returns (D256 memory)\n {\n return D256({ value: 0 });\n }\n\n function one()\n internal\n pure\n returns (D256 memory)\n {\n return D256({ value: BASE });\n }\n\n function from(\n uint256 a\n )\n internal\n pure\n returns (D256 memory)\n {\n return D256({ value: a.mul(BASE) });\n }\n\n function ratio(\n uint256 a,\n uint256 b\n )\n internal\n pure\n returns (D256 memory)\n {\n return D256({ value: getPartial(a, BASE, b) });\n }\n\n // ============ Self Functions ============\n\n function add(\n D256 memory self,\n uint256 b\n )\n internal\n pure\n returns (D256 memory)\n {\n return D256({ value: self.value.add(b.mul(BASE)) });\n }\n\n function sub(\n D256 memory self,\n uint256 b\n )\n internal\n pure\n returns (D256 memory)\n {\n return D256({ value: self.value.sub(b.mul(BASE)) });\n }\n\n function sub(\n D256 memory self,\n uint256 b,\n string memory reason\n )\n internal\n pure\n returns (D256 memory)\n {\n return D256({ value: self.value.sub(b.mul(BASE), reason) });\n }\n\n function mul(\n D256 memory self,\n uint256 b\n )\n internal\n pure\n returns (D256 memory)\n {\n return D256({ value: self.value.mul(b) });\n }\n\n function div(\n D256 memory self,\n uint256 b\n )\n internal\n pure\n returns (D256 memory)\n {\n return D256({ value: self.value.div(b) });\n }\n\n function pow(\n D256 memory self,\n uint256 b\n )\n internal\n pure\n returns (D256 memory)\n {\n if (b == 0) {\n return one();\n }\n\n D256 memory temp = D256({ value: self.value });\n for (uint256 i = 1; i < b; ++i) {\n temp = mul(temp, self);\n }\n\n return temp;\n }\n\n function add(\n D256 memory self,\n D256 memory b\n )\n internal\n pure\n returns (D256 memory)\n {\n return D256({ value: self.value.add(b.value) });\n }\n\n function sub(\n D256 memory self,\n D256 memory b\n )\n internal\n pure\n returns (D256 memory)\n {\n return D256({ value: self.value.sub(b.value) });\n }\n\n function sub(\n D256 memory self,\n D256 memory b,\n string memory reason\n )\n internal\n pure\n returns (D256 memory)\n {\n return D256({ value: self.value.sub(b.value, reason) });\n }\n\n function mul(\n D256 memory self,\n D256 memory b\n )\n internal\n pure\n returns (D256 memory)\n {\n return D256({ value: getPartial(self.value, b.value, BASE) });\n }\n\n function div(\n D256 memory self,\n D256 memory b\n )\n internal\n pure\n returns (D256 memory)\n {\n return D256({ value: getPartial(self.value, BASE, b.value) });\n }\n\n function equals(D256 memory self, D256 memory b) internal pure returns (bool) {\n return self.value == b.value;\n }\n\n function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {\n return compareTo(self, b) == 2;\n }\n\n function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {\n return compareTo(self, b) == 0;\n }\n\n function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {\n return compareTo(self, b) > 0;\n }\n\n function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {\n return compareTo(self, b) < 2;\n }\n\n function isZero(D256 memory self) internal pure returns (bool) {\n return self.value == 0;\n }\n\n function asUint256(D256 memory self) internal pure returns (uint256) {\n return self.value.div(BASE);\n }\n\n // ============ Core Methods ============\n\n function getPartial(\n uint256 target,\n uint256 numerator,\n uint256 denominator\n )\n private\n pure\n returns (uint256)\n {\n return target.mul(numerator).div(denominator);\n }\n\n function compareTo(\n D256 memory a,\n D256 memory b\n )\n private\n pure\n returns (uint256)\n {\n if (a.value == b.value) {\n return 1;\n }\n return a.value > b.value ? 2 : 0;\n }\n}\n" }, "contracts/libraries/LibAppStorage.sol": { "content": "/*\n SPDX-License-Identifier: MIT\n*/\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport \"../farm/AppStorage.sol\";\n\n/**\n * @author Publius\n * @title App Storage Library allows libaries to access Beanstalk's state.\n**/\nlibrary LibAppStorage {\n\n function diamondStorage() internal pure returns (AppStorage storage ds) {\n assembly {\n ds.slot := 0\n }\n }\n\n}\n" }, "contracts/libraries/LibDiamond.sol": { "content": "/*\n SPDX-License-Identifier: MIT\n*/\n\npragma experimental ABIEncoderV2;\npragma solidity =0.7.6;\n/******************************************************************************\\\n* Author: Nick Mudge (https://twitter.com/mudgen)\n* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535\n/******************************************************************************/\n\nimport {IDiamondCut} from \"../interfaces/IDiamondCut.sol\";\nimport {IDiamondLoupe} from \"../interfaces/IDiamondLoupe.sol\";\nimport {IERC165} from \"../interfaces/IERC165.sol\";\n\nlibrary LibDiamond {\n bytes32 constant DIAMOND_STORAGE_POSITION = keccak256(\"diamond.standard.diamond.storage\");\n\n struct FacetAddressAndPosition {\n address facetAddress;\n uint96 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array\n }\n\n struct FacetFunctionSelectors {\n bytes4[] functionSelectors;\n uint256 facetAddressPosition; // position of facetAddress in facetAddresses array\n }\n\n struct DiamondStorage {\n // maps function selector to the facet address and\n // the position of the selector in the facetFunctionSelectors.selectors array\n mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition;\n // maps facet addresses to function selectors\n mapping(address => FacetFunctionSelectors) facetFunctionSelectors;\n // facet addresses\n address[] facetAddresses;\n // Used to query if a contract implements an interface.\n // Used to implement ERC-165.\n mapping(bytes4 => bool) supportedInterfaces;\n // owner of the contract\n address contractOwner;\n }\n\n function diamondStorage() internal pure returns (DiamondStorage storage ds) {\n bytes32 position = DIAMOND_STORAGE_POSITION;\n assembly {\n ds.slot := position\n }\n }\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n function setContractOwner(address _newOwner) internal {\n DiamondStorage storage ds = diamondStorage();\n address previousOwner = ds.contractOwner;\n ds.contractOwner = _newOwner;\n emit OwnershipTransferred(previousOwner, _newOwner);\n }\n\n function contractOwner() internal view returns (address contractOwner_) {\n contractOwner_ = diamondStorage().contractOwner;\n }\n\n function enforceIsOwnerOrContract() internal view {\n require(msg.sender == diamondStorage().contractOwner ||\n msg.sender == address(this), \"LibDiamond: Must be contract or owner\"\n );\n }\n\n function enforceIsContractOwner() internal view {\n require(msg.sender == diamondStorage().contractOwner, \"LibDiamond: Must be contract owner\");\n }\n\n event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata);\n\n function addDiamondFunctions(\n address _diamondCutFacet,\n address _diamondLoupeFacet\n ) internal {\n IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](2);\n bytes4[] memory functionSelectors = new bytes4[](1);\n functionSelectors[0] = IDiamondCut.diamondCut.selector;\n cut[0] = IDiamondCut.FacetCut({facetAddress: _diamondCutFacet, action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors});\n functionSelectors = new bytes4[](5);\n functionSelectors[0] = IDiamondLoupe.facets.selector;\n functionSelectors[1] = IDiamondLoupe.facetFunctionSelectors.selector;\n functionSelectors[2] = IDiamondLoupe.facetAddresses.selector;\n functionSelectors[3] = IDiamondLoupe.facetAddress.selector;\n functionSelectors[4] = IERC165.supportsInterface.selector;\n cut[1] = IDiamondCut.FacetCut({\n facetAddress: _diamondLoupeFacet,\n action: IDiamondCut.FacetCutAction.Add,\n functionSelectors: functionSelectors\n });\n diamondCut(cut, address(0), \"\");\n }\n\n // Internal function version of diamondCut\n function diamondCut(\n IDiamondCut.FacetCut[] memory _diamondCut,\n address _init,\n bytes memory _calldata\n ) internal {\n for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {\n IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action;\n if (action == IDiamondCut.FacetCutAction.Add) {\n addFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);\n } else if (action == IDiamondCut.FacetCutAction.Replace) {\n replaceFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);\n } else if (action == IDiamondCut.FacetCutAction.Remove) {\n removeFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);\n } else {\n revert(\"LibDiamondCut: Incorrect FacetCutAction\");\n }\n }\n emit DiamondCut(_diamondCut, _init, _calldata);\n initializeDiamondCut(_init, _calldata);\n }\n\n function addFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {\n require(_functionSelectors.length > 0, \"LibDiamondCut: No selectors in facet to cut\");\n DiamondStorage storage ds = diamondStorage(); \n require(_facetAddress != address(0), \"LibDiamondCut: Add facet can't be address(0)\");\n uint96 selectorPosition = uint96(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length);\n // add new facet address if it does not exist\n if (selectorPosition == 0) {\n addFacet(ds, _facetAddress); \n }\n for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {\n bytes4 selector = _functionSelectors[selectorIndex];\n address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;\n require(oldFacetAddress == address(0), \"LibDiamondCut: Can't add function that already exists\");\n addFunction(ds, selector, selectorPosition, _facetAddress);\n selectorPosition++;\n }\n }\n\n function replaceFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {\n require(_functionSelectors.length > 0, \"LibDiamondCut: No selectors in facet to cut\");\n DiamondStorage storage ds = diamondStorage();\n require(_facetAddress != address(0), \"LibDiamondCut: Add facet can't be address(0)\");\n uint96 selectorPosition = uint96(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length);\n // add new facet address if it does not exist\n if (selectorPosition == 0) {\n addFacet(ds, _facetAddress);\n }\n for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {\n bytes4 selector = _functionSelectors[selectorIndex];\n address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;\n require(oldFacetAddress != _facetAddress, \"LibDiamondCut: Can't replace function with same function\");\n removeFunction(ds, oldFacetAddress, selector);\n addFunction(ds, selector, selectorPosition, _facetAddress);\n selectorPosition++;\n }\n }\n\n function removeFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {\n require(_functionSelectors.length > 0, \"LibDiamondCut: No selectors in facet to cut\");\n DiamondStorage storage ds = diamondStorage();\n // if function does not exist then do nothing and return\n require(_facetAddress == address(0), \"LibDiamondCut: Remove facet address must be address(0)\");\n for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {\n bytes4 selector = _functionSelectors[selectorIndex];\n address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;\n removeFunction(ds, oldFacetAddress, selector);\n }\n }\n\n function addFacet(DiamondStorage storage ds, address _facetAddress) internal {\n enforceHasContractCode(_facetAddress, \"LibDiamondCut: New facet has no code\");\n ds.facetFunctionSelectors[_facetAddress].facetAddressPosition = ds.facetAddresses.length;\n ds.facetAddresses.push(_facetAddress);\n } \n\n\n function addFunction(DiamondStorage storage ds, bytes4 _selector, uint96 _selectorPosition, address _facetAddress) internal {\n ds.selectorToFacetAndPosition[_selector].functionSelectorPosition = _selectorPosition;\n ds.facetFunctionSelectors[_facetAddress].functionSelectors.push(_selector);\n ds.selectorToFacetAndPosition[_selector].facetAddress = _facetAddress;\n }\n\n function removeFunction(DiamondStorage storage ds, address _facetAddress, bytes4 _selector) internal { \n require(_facetAddress != address(0), \"LibDiamondCut: Can't remove function that doesn't exist\");\n // an immutable function is a function defined directly in a diamond\n require(_facetAddress != address(this), \"LibDiamondCut: Can't remove immutable function\");\n // replace selector with last selector, then delete last selector\n uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition;\n uint256 lastSelectorPosition = ds.facetFunctionSelectors[_facetAddress].functionSelectors.length - 1;\n // if not the same then replace _selector with lastSelector\n if (selectorPosition != lastSelectorPosition) {\n bytes4 lastSelector = ds.facetFunctionSelectors[_facetAddress].functionSelectors[lastSelectorPosition];\n ds.facetFunctionSelectors[_facetAddress].functionSelectors[selectorPosition] = lastSelector;\n ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint96(selectorPosition);\n }\n // delete the last selector\n ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop();\n delete ds.selectorToFacetAndPosition[_selector];\n\n // if no more selectors for facet address then delete the facet address\n if (lastSelectorPosition == 0) {\n // replace facet address with last facet address and delete last facet address\n uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1;\n uint256 facetAddressPosition = ds.facetFunctionSelectors[_facetAddress].facetAddressPosition;\n if (facetAddressPosition != lastFacetAddressPosition) {\n address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition];\n ds.facetAddresses[facetAddressPosition] = lastFacetAddress;\n ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = facetAddressPosition;\n }\n ds.facetAddresses.pop();\n delete ds.facetFunctionSelectors[_facetAddress].facetAddressPosition;\n }\n }\n\n function initializeDiamondCut(address _init, bytes memory _calldata) internal {\n if (_init == address(0)) {\n require(_calldata.length == 0, \"LibDiamondCut: _init is address(0) but_calldata is not empty\");\n } else {\n require(_calldata.length > 0, \"LibDiamondCut: _calldata is empty but _init is not address(0)\");\n if (_init != address(this)) {\n enforceHasContractCode(_init, \"LibDiamondCut: _init address has no code\");\n }\n (bool success, bytes memory error) = _init.delegatecall(_calldata);\n if (!success) {\n if (error.length > 0) {\n // bubble up the error\n revert(string(error));\n } else {\n revert(\"LibDiamondCut: _init function reverted\");\n }\n }\n }\n }\n\n function enforceHasContractCode(address _contract, string memory _errorMessage) internal view {\n uint256 contractSize;\n assembly {\n contractSize := extcodesize(_contract)\n }\n require(contractSize > 0, _errorMessage);\n }\n}" }, "contracts/libraries/Silo/LibWhitelist.sol": { "content": "/*\n SPDX-License-Identifier: MIT\n*/\n\npragma solidity =0.7.6;\npragma experimental ABIEncoderV2;\n\nimport \"../../C.sol\";\nimport \"../LibAppStorage.sol\";\n\n/**\n * @author Publius\n * @title LibWhitelist handles the whitelisting of different tokens.\n **/\n\ninterface IBS {\n function lusdToBDV(uint256 amount) external view returns (uint256);\n\n function curveToBDV(uint256 amount) external view returns (uint256);\n\n function beanToBDV(uint256 amount) external pure returns (uint256);\n\n function unripeBeanToBDV(uint256 amount) external view returns (uint256);\n\n function unripeLPToBDV(uint256 amount) external view returns (uint256);\n}\n\nlibrary LibWhitelist {\n\n event WhitelistToken(\n address indexed token,\n bytes4 selector,\n uint256 seeds,\n uint256 stalk\n );\n\n event DewhitelistToken(address indexed token);\n\n uint32 private constant BEAN_3CRV_STALK = 10000;\n uint32 private constant BEAN_3CRV_SEEDS = 4;\n\n uint32 private constant BEAN_STALK = 10000;\n uint32 private constant BEAN_SEEDS = 2;\n\n function whitelistPools() internal {\n whitelistBean3Crv();\n whitelistBean();\n whitelistUnripeBean();\n whitelistUnripeLP();\n }\n\n function whitelistBean3Crv() internal {\n whitelistToken(\n C.curveMetapoolAddress(),\n IBS.curveToBDV.selector,\n BEAN_3CRV_STALK,\n BEAN_3CRV_SEEDS\n );\n }\n\n function whitelistBean() internal {\n whitelistToken(\n C.beanAddress(),\n IBS.beanToBDV.selector,\n BEAN_STALK,\n BEAN_SEEDS\n );\n }\n\n function whitelistUnripeBean() internal {\n whitelistToken(\n C.unripeBeanAddress(),\n IBS.unripeBeanToBDV.selector,\n BEAN_STALK,\n BEAN_SEEDS\n );\n }\n\n function whitelistUnripeLP() internal {\n whitelistToken(\n C.unripeLPAddress(),\n IBS.unripeLPToBDV.selector,\n BEAN_3CRV_STALK,\n BEAN_3CRV_SEEDS\n );\n }\n\n function dewhitelistToken(address token) internal {\n AppStorage storage s = LibAppStorage.diamondStorage();\n delete s.ss[token];\n emit DewhitelistToken(token);\n }\n\n function whitelistToken(\n address token,\n bytes4 selector,\n uint32 stalk,\n uint32 seeds\n ) internal {\n AppStorage storage s = LibAppStorage.diamondStorage();\n s.ss[token].selector = selector;\n s.ss[token].stalk = stalk;\n s.ss[token].seeds = seeds;\n\n emit WhitelistToken(token, selector, stalk, seeds);\n }\n}\n" }, "contracts/seraph/SeraphProtected.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.5.0 <=0.9.0;\n\ninterface ISeraph {\n function checkEnter(address, bytes4, bytes calldata, uint256) external;\n function checkLeave(bytes4) external;\n}\n\nabstract contract SeraphProtected {\n\n ISeraph constant internal _seraph = ISeraph(0xAac09eEdCcf664a9A6a594Fc527A0A4eC6cc2788);\n\n modifier withSeraph() {\n _seraph.checkEnter(msg.sender, msg.sig, msg.data, 0);\n _;\n _seraph.checkLeave(msg.sig);\n }\n\n modifier withSeraphPayable() {\n _seraph.checkEnter(msg.sender, msg.sig, msg.data, msg.value);\n _;\n _seraph.checkLeave(msg.sig);\n }\n}" } }, "settings": { "optimizer": { "enabled": true, "runs": 1000 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} } }