{ "language": "Solidity", "settings": { "evmVersion": "istanbul", "libraries": {}, "metadata": { "bytecodeHash": "ipfs", "useLiteralContent": true }, "optimizer": { "details": { "constantOptimizer": true, "cse": true, "deduplicate": true, "jumpdestRemover": true, "orderLiterals": true, "peephole": true, "yul": false }, "runs": 200 }, "remappings": [], "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } } }, "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/ERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../../utils/Context.sol\";\nimport \"./IERC20.sol\";\nimport \"../../math/SafeMath.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20 {\n using SafeMath for uint256;\n\n mapping (address => uint256) private _balances;\n\n mapping (address => mapping (address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n uint8 private _decimals;\n\n /**\n * @dev Sets the values for {name} and {symbol}, initializes {decimals} with\n * a default value of 18.\n *\n * To select a different value for {decimals}, use {_setupDecimals}.\n *\n * All three of these values are immutable: they can only be set once during\n * construction.\n */\n constructor (string memory name_, string memory symbol_) public {\n _name = name_;\n _symbol = symbol_;\n _decimals = 18;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5,05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is\n * called.\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual returns (uint8) {\n return _decimals;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `recipient` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n _transfer(_msgSender(), recipient, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n _approve(_msgSender(), spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * Requirements:\n *\n * - `sender` and `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n * - the caller must have allowance for ``sender``'s tokens of at least\n * `amount`.\n */\n function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\n _transfer(sender, recipient, amount);\n _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n return true;\n }\n\n /**\n * @dev Moves tokens `amount` from `sender` to `recipient`.\n *\n * This is internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `sender` cannot be the zero address.\n * - `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n */\n function _transfer(address sender, address recipient, uint256 amount) internal virtual {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(sender, recipient, amount);\n\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n _balances[recipient] = _balances[recipient].add(amount);\n emit Transfer(sender, recipient, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply = _totalSupply.add(amount);\n _balances[account] = _balances[account].add(amount);\n emit Transfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n _totalSupply = _totalSupply.sub(amount);\n emit Transfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(address owner, address spender, uint256 amount) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Sets {decimals} to a value other than the default one of 18.\n *\n * WARNING: This function should only be called from the constructor. Most\n * applications that interact with token contracts will not expect\n * {decimals} to ever change, and may work incorrectly if it does.\n */\n function _setupDecimals(uint8 decimals_) internal virtual {\n _decimals = decimals_;\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be to transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }\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/token/ERC20/SafeERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"../../math/SafeMath.sol\";\nimport \"../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using SafeMath for uint256;\n using Address for address;\n\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(IERC20 token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n // solhint-disable-next-line max-line-length\n require((value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).add(value);\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).sub(value, \"SafeERC20: decreased allowance below zero\");\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) { // Return data is optional\n // solhint-disable-next-line max-line-length\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" }, "@openzeppelin/contracts/utils/Address.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.2 <0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{ value: amount }(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{ value: value }(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.staticcall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" }, "@openzeppelin/contracts/utils/Context.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n}\n" }, "@openzeppelin/contracts/utils/ReentrancyGuard.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n uint256 private _status;\n\n constructor () internal {\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and make it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n // On the first call to nonReentrant, _notEntered will be true\n require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _status = _ENTERED;\n\n _;\n\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n _status = _NOT_ENTERED;\n }\n}\n" }, "contracts/persistent/dispatcher/IDispatcher.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n\n (c) Enzyme Council \n\n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\n\n/// @title IDispatcher Interface\n/// @author Enzyme Council \ninterface IDispatcher {\n function cancelMigration(address _vaultProxy, bool _bypassFailure) external;\n\n function claimOwnership() external;\n\n function deployVaultProxy(\n address _vaultLib,\n address _owner,\n address _vaultAccessor,\n string calldata _fundName\n ) external returns (address vaultProxy_);\n\n function executeMigration(address _vaultProxy, bool _bypassFailure) external;\n\n function getCurrentFundDeployer() external view returns (address currentFundDeployer_);\n\n function getFundDeployerForVaultProxy(address _vaultProxy)\n external\n view\n returns (address fundDeployer_);\n\n function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)\n external\n view\n returns (\n address nextFundDeployer_,\n address nextVaultAccessor_,\n address nextVaultLib_,\n uint256 executableTimestamp_\n );\n\n function getMigrationTimelock() external view returns (uint256 migrationTimelock_);\n\n function getNominatedOwner() external view returns (address nominatedOwner_);\n\n function getOwner() external view returns (address owner_);\n\n function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_);\n\n function getTimelockRemainingForMigrationRequest(address _vaultProxy)\n external\n view\n returns (uint256 secondsRemaining_);\n\n function hasExecutableMigrationRequest(address _vaultProxy)\n external\n view\n returns (bool hasExecutableRequest_);\n\n function hasMigrationRequest(address _vaultProxy)\n external\n view\n returns (bool hasMigrationRequest_);\n\n function removeNominatedOwner() external;\n\n function setCurrentFundDeployer(address _nextFundDeployer) external;\n\n function setMigrationTimelock(uint256 _nextTimelock) external;\n\n function setNominatedOwner(address _nextNominatedOwner) external;\n\n function setSharesTokenSymbol(string calldata _nextSymbol) external;\n\n function signalMigration(\n address _vaultProxy,\n address _nextVaultAccessor,\n address _nextVaultLib,\n bool _bypassFailure\n ) external;\n}\n" }, "contracts/release/extensions/integration-manager/IIntegrationManager.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n\n (c) Enzyme Council \n\n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\n\n/// @title IIntegrationManager interface\n/// @author Enzyme Council \n/// @notice Interface for the IntegrationManager\ninterface IIntegrationManager {\n enum SpendAssetsHandleType {\n None,\n Approve,\n Transfer\n }\n}\n" }, "contracts/release/extensions/integration-manager/integrations/IIntegrationAdapter.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n\n (c) Enzyme Council \n\n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\n\nimport \"../IIntegrationManager.sol\";\n\n/// @title Integration Adapter interface\n/// @author Enzyme Council \n/// @notice Interface for all integration adapters\ninterface IIntegrationAdapter {\n function parseAssetsForAction(\n address _vaultProxy,\n bytes4 _selector,\n bytes calldata _encodedCallArgs\n )\n external\n view\n returns (\n IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,\n address[] memory spendAssets_,\n uint256[] memory spendAssetAmounts_,\n address[] memory incomingAssets_,\n uint256[] memory minIncomingAssetAmounts_\n );\n}\n" }, "contracts/release/extensions/integration-manager/integrations/adapters/AuraBalancerV2LpStakingAdapter.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"../../../../infrastructure/staking-wrappers/aura-balancer-v2-lp/AuraBalancerV2LpStakingWrapperFactory.sol\";\nimport \"../utils/actions/StakingWrapperActionsMixin.sol\";\nimport \"../utils/bases/BalancerV2LiquidityAdapterBase.sol\";\n\n/// @title AuraBalancerV2LpStakingAdapter Contract\n/// @author Enzyme Council \n/// @notice Adapter for staking Balancer pool tokens via Aura\n/// with optional combined end-to-end liquidity provision via Balancer\ncontract AuraBalancerV2LpStakingAdapter is\n BalancerV2LiquidityAdapterBase,\n StakingWrapperActionsMixin\n{\n AuraBalancerV2LpStakingWrapperFactory private immutable STAKING_WRAPPER_FACTORY_CONTRACT;\n\n constructor(\n address _integrationManager,\n address _balancerVault,\n address _stakingWrapperFactory\n ) public BalancerV2LiquidityAdapterBase(_integrationManager, _balancerVault) {\n STAKING_WRAPPER_FACTORY_CONTRACT = AuraBalancerV2LpStakingWrapperFactory(\n _stakingWrapperFactory\n );\n }\n\n ////////////////////////////////\n // REQUIRED VIRTUAL FUNCTIONS //\n ////////////////////////////////\n\n /// @dev Logic to claim rewards for a given staking token\n function __claimRewards(address _vaultProxy, address _stakingToken) internal override {\n __stakingWrapperClaimRewardsFor(_stakingToken, _vaultProxy);\n }\n\n /// @dev Logic to get the BPT address for a given staking token.\n /// For this adapter, the staking token is validated herein.\n function __getBptForStakingToken(address _stakingToken)\n internal\n view\n override\n returns (address bpt_)\n {\n return STAKING_WRAPPER_FACTORY_CONTRACT.getCurveLpTokenForWrapper(_stakingToken);\n }\n\n /// @dev Logic to stake BPT to a given staking token.\n /// Staking is always the last action and thus always sent to the _vaultProxy\n /// (rather than a more generically-named `_recipient`).\n function __stake(\n address _vaultProxy,\n address _stakingToken,\n uint256 _bptAmount\n ) internal override {\n __stakingWrapperStake(\n _stakingToken,\n _vaultProxy,\n _bptAmount,\n __getBptForStakingToken(_stakingToken)\n );\n }\n\n /// @dev Logic to unstake BPT from a given staking token\n function __unstake(\n address _vaultProxy,\n address _recipient,\n address _stakingToken,\n uint256 _bptAmount\n ) internal override {\n __stakingWrapperUnstake(_stakingToken, _vaultProxy, _recipient, _bptAmount, false);\n }\n\n ///////////////\n // OVERRIDES //\n ///////////////\n\n /// @dev Helper function to parse spend and incoming assets from encoded call args\n /// during unstake() calls.\n /// Overridden to use `SpendAssetsHandleType.Approve`.\n function __parseAssetsForUnstake(bytes calldata _actionData)\n internal\n view\n override\n returns (\n IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,\n address[] memory spendAssets_,\n uint256[] memory spendAssetAmounts_,\n address[] memory incomingAssets_,\n uint256[] memory minIncomingAssetAmounts_\n )\n {\n (, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_) = super\n .__parseAssetsForUnstake(_actionData);\n\n // SpendAssetsHandleType is `Approve`, since staking wrapper allows unstaking on behalf\n return (\n IIntegrationManager.SpendAssetsHandleType.Approve,\n spendAssets_,\n spendAssetAmounts_,\n incomingAssets_,\n minIncomingAssetAmounts_\n );\n }\n\n /// @dev Helper function to parse spend and incoming assets from encoded call args\n /// during unstakeAndRedeem() calls\n function __parseAssetsForUnstakeAndRedeem(bytes calldata _actionData)\n internal\n view\n override\n returns (\n IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,\n address[] memory spendAssets_,\n uint256[] memory spendAssetAmounts_,\n address[] memory incomingAssets_,\n uint256[] memory minIncomingAssetAmounts_\n )\n {\n (, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_) = super\n .__parseAssetsForUnstakeAndRedeem(_actionData);\n\n // SpendAssetsHandleType is `Approve`, since staking wrapper allows unstaking on behalf\n return (\n IIntegrationManager.SpendAssetsHandleType.Approve,\n spendAssets_,\n spendAssetAmounts_,\n incomingAssets_,\n minIncomingAssetAmounts_\n );\n }\n}\n" }, "contracts/release/extensions/integration-manager/integrations/utils/AdapterBase.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n\n (c) Enzyme Council \n\n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/SafeERC20.sol\";\nimport \"../../../../utils/AssetHelpers.sol\";\nimport \"../IIntegrationAdapter.sol\";\nimport \"./IntegrationSelectors.sol\";\n\n/// @title AdapterBase Contract\n/// @author Enzyme Council \n/// @notice A base contract for integration adapters\nabstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors, AssetHelpers {\n using SafeERC20 for ERC20;\n\n address internal immutable INTEGRATION_MANAGER;\n\n /// @dev Provides a standard implementation for transferring incoming assets\n /// from an adapter to a VaultProxy at the end of an adapter action\n modifier postActionIncomingAssetsTransferHandler(\n address _vaultProxy,\n bytes memory _assetData\n ) {\n _;\n\n (, , address[] memory incomingAssets) = __decodeAssetData(_assetData);\n\n __pushFullAssetBalances(_vaultProxy, incomingAssets);\n }\n\n /// @dev Provides a standard implementation for transferring unspent spend assets\n /// from an adapter to a VaultProxy at the end of an adapter action\n modifier postActionSpendAssetsTransferHandler(address _vaultProxy, bytes memory _assetData) {\n _;\n\n (address[] memory spendAssets, , ) = __decodeAssetData(_assetData);\n\n __pushFullAssetBalances(_vaultProxy, spendAssets);\n }\n\n modifier onlyIntegrationManager() {\n require(\n msg.sender == INTEGRATION_MANAGER,\n \"Only the IntegrationManager can call this function\"\n );\n _;\n }\n\n constructor(address _integrationManager) public {\n INTEGRATION_MANAGER = _integrationManager;\n }\n\n // INTERNAL FUNCTIONS\n\n /// @dev Helper to decode the _assetData param passed to adapter call\n function __decodeAssetData(bytes memory _assetData)\n internal\n pure\n returns (\n address[] memory spendAssets_,\n uint256[] memory spendAssetAmounts_,\n address[] memory incomingAssets_\n )\n {\n return abi.decode(_assetData, (address[], uint256[], address[]));\n }\n\n ///////////////////\n // STATE GETTERS //\n ///////////////////\n\n /// @notice Gets the `INTEGRATION_MANAGER` variable\n /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value\n function getIntegrationManager() external view returns (address integrationManager_) {\n return INTEGRATION_MANAGER;\n }\n}\n" }, "contracts/release/extensions/integration-manager/integrations/utils/IntegrationSelectors.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n\n (c) Enzyme Council \n\n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\n\n/// @title IntegrationSelectors Contract\n/// @author Enzyme Council \n/// @notice Selectors for integration actions\n/// @dev Selectors are created from their signatures rather than hardcoded for easy verification\nabstract contract IntegrationSelectors {\n // Trading\n bytes4 public constant TAKE_MULTIPLE_ORDERS_SELECTOR =\n bytes4(keccak256(\"takeMultipleOrders(address,bytes,bytes)\"));\n bytes4 public constant TAKE_ORDER_SELECTOR =\n bytes4(keccak256(\"takeOrder(address,bytes,bytes)\"));\n\n // Lending\n bytes4 public constant LEND_SELECTOR = bytes4(keccak256(\"lend(address,bytes,bytes)\"));\n bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256(\"redeem(address,bytes,bytes)\"));\n\n // Staking\n bytes4 public constant STAKE_SELECTOR = bytes4(keccak256(\"stake(address,bytes,bytes)\"));\n bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256(\"unstake(address,bytes,bytes)\"));\n\n // Rewards\n bytes4 public constant CLAIM_REWARDS_SELECTOR =\n bytes4(keccak256(\"claimRewards(address,bytes,bytes)\"));\n\n // Combined\n bytes4 public constant LEND_AND_STAKE_SELECTOR =\n bytes4(keccak256(\"lendAndStake(address,bytes,bytes)\"));\n bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR =\n bytes4(keccak256(\"unstakeAndRedeem(address,bytes,bytes)\"));\n}\n" }, "contracts/release/extensions/integration-manager/integrations/utils/actions/BalancerV2ActionsMixin.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n (c) Enzyme Council \n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\n\nimport \"../../../../../interfaces/IBalancerV2Vault.sol\";\n\n/// @title BalancerV2ActionsMixin Contract\n/// @author Enzyme Council \n/// @notice Mixin contract for interacting with BalancerV2\nabstract contract BalancerV2ActionsMixin {\n IBalancerV2Vault internal immutable BALANCER_VAULT_CONTRACT;\n\n constructor(address _balancerVault) public {\n BALANCER_VAULT_CONTRACT = IBalancerV2Vault(_balancerVault);\n }\n\n /// @dev Helper to add liquidity\n function __balancerV2Lend(\n bytes32 _poolId,\n address _sender,\n address _recipient,\n IBalancerV2Vault.PoolBalanceChange memory _request\n ) internal {\n BALANCER_VAULT_CONTRACT.joinPool(_poolId, _sender, _recipient, _request);\n }\n\n /// @dev Helper to remove liquidity\n function __balancerV2Redeem(\n bytes32 _poolId,\n address _sender,\n address payable _recipient,\n IBalancerV2Vault.PoolBalanceChange memory _request\n ) internal {\n BALANCER_VAULT_CONTRACT.exitPool(_poolId, _sender, _recipient, _request);\n }\n}\n" }, "contracts/release/extensions/integration-manager/integrations/utils/actions/StakingWrapperActionsMixin.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n\n (c) Enzyme Council \n\n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\n\nimport \"../../../../../infrastructure/staking-wrappers/IStakingWrapper.sol\";\nimport \"../../../../../utils/AssetHelpers.sol\";\n\n/// @title StakingWrapperActionsMixin Contract\n/// @author Enzyme Council \n/// @notice Mixin contract for interacting with IStakingWrapper implementations\nabstract contract StakingWrapperActionsMixin is AssetHelpers {\n /// @dev Helper to claim rewards via a IStakingWrapper implementation\n function __stakingWrapperClaimRewardsFor(address _wrapper, address _for) internal {\n IStakingWrapper(_wrapper).claimRewardsFor(_for);\n }\n\n /// @dev Helper to stake via a IStakingWrapper implementation\n function __stakingWrapperStake(\n address _wrapper,\n address _to,\n uint256 _amount,\n address _outgoingAsset\n ) internal {\n __approveAssetMaxAsNeeded(_outgoingAsset, _wrapper, _amount);\n IStakingWrapper(_wrapper).depositTo(_to, _amount);\n }\n\n /// @dev Helper to unstake via a IStakingWrapper implementation\n function __stakingWrapperUnstake(\n address _wrapper,\n address _from,\n address _to,\n uint256 _amount,\n bool _claimRewards\n ) internal {\n IStakingWrapper(_wrapper).withdrawToOnBehalf(_from, _to, _amount, _claimRewards);\n }\n}\n" }, "contracts/release/extensions/integration-manager/integrations/utils/bases/BalancerV2LiquidityAdapterBase.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n (c) Enzyme Council \n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"../../../../../interfaces/IBalancerV2Vault.sol\";\nimport \"../../../../../utils/AddressArrayLib.sol\";\nimport \"../../utils/actions/BalancerV2ActionsMixin.sol\";\nimport \"../../utils/AdapterBase.sol\";\n\n/// @title BalancerV2LiquidityAdapterBase Contract\n/// @author Enzyme Council \n/// @notice Base adapter for liquidity provision in Balancer V2 pools.\n/// Implementing contracts can allow staking via Balancer gauges, Aura, etc.\n/// @dev Rewards tokens are not included as incoming assets for claimRewards()\nabstract contract BalancerV2LiquidityAdapterBase is AdapterBase, BalancerV2ActionsMixin {\n using AddressArrayLib for address[];\n\n constructor(address _integrationManager, address _balancerVault)\n public\n AdapterBase(_integrationManager)\n BalancerV2ActionsMixin(_balancerVault)\n {}\n\n ////////////////////////////////\n // REQUIRED VIRTUAL FUNCTIONS //\n ////////////////////////////////\n\n /// @dev Logic to claim rewards for a given staking token\n function __claimRewards(address _vaultProxy, address _stakingToken) internal virtual;\n\n /// @dev Logic to get the BPT address for a given staking token.\n /// Implementations should pre-validate whether the staking token is valid,\n /// when reasonable.\n function __getBptForStakingToken(address _stakingToken)\n internal\n view\n virtual\n returns (address bpt_);\n\n /// @dev Logic to stake BPT to a given staking token.\n /// Staking is always the last action and thus always sent to the _vaultProxy\n /// (rather than a more generically-named `_recipient`).\n function __stake(\n address _vaultProxy,\n address _stakingToken,\n uint256 _bptAmount\n ) internal virtual;\n\n /// @dev Logic to unstake BPT from a given staking token\n function __unstake(\n address _vaultProxy,\n address _recipient,\n address _stakingToken,\n uint256 _bptAmount\n ) internal virtual;\n\n /////////////\n // ACTIONS //\n /////////////\n\n // EXTERNAL FUNCTIONS\n\n /// @notice Claims all rewards\n /// @param _vaultProxy The VaultProxy of the calling fund\n /// @param _actionData Data specific to this action\n /// @dev Needs `onlyIntegrationManager` because Minter claiming permission is given by the fund\n function claimRewards(\n address _vaultProxy,\n bytes calldata _actionData,\n bytes calldata\n ) external onlyIntegrationManager {\n __claimRewards(_vaultProxy, __decodeClaimRewardsCallArgs(_actionData));\n }\n\n /// @notice Lends assets for LP tokens, then stakes the received LP tokens\n /// @param _vaultProxy The VaultProxy of the calling fund\n /// @param _actionData Data specific to this action\n function lendAndStake(\n address _vaultProxy,\n bytes calldata _actionData,\n bytes calldata\n ) external onlyIntegrationManager {\n (\n address stakingToken,\n bytes32 poolId,\n ,\n address[] memory spendAssets,\n uint256[] memory spendAssetAmounts,\n IBalancerV2Vault.PoolBalanceChange memory request\n ) = __decodeCombinedActionCallArgs(_actionData);\n\n __lend(address(this), poolId, spendAssets, spendAssetAmounts, request);\n\n __stake(\n _vaultProxy,\n stakingToken,\n ERC20(__parseBalancerPoolAddress(poolId)).balanceOf(address(this))\n );\n\n // There can be different join/exit options per Balancer pool type,\n // some of which involve spending only up-to-max amounts\n __pushFullAssetBalances(_vaultProxy, spendAssets);\n }\n\n /// @notice Stakes LP tokens\n /// @param _vaultProxy The VaultProxy of the calling fund\n /// @param _actionData Data specific to this action\n function stake(\n address _vaultProxy,\n bytes calldata _actionData,\n bytes calldata\n ) external onlyIntegrationManager {\n (address stakingToken, uint256 bptAmount) = __decodeStakingActionCallArgs(_actionData);\n\n __stake(_vaultProxy, stakingToken, bptAmount);\n }\n\n /// @notice Unstakes LP tokens\n /// @param _vaultProxy The VaultProxy of the calling fund\n /// @param _actionData Data specific to this action\n function unstake(\n address _vaultProxy,\n bytes calldata _actionData,\n bytes calldata\n ) external onlyIntegrationManager {\n (address stakingToken, uint256 bptAmount) = __decodeStakingActionCallArgs(_actionData);\n\n __unstake(_vaultProxy, _vaultProxy, stakingToken, bptAmount);\n }\n\n /// @notice Unstakes LP tokens, then redeems them\n /// @param _vaultProxy The VaultProxy of the calling fund\n /// @param _actionData Data specific to this action\n function unstakeAndRedeem(\n address _vaultProxy,\n bytes calldata _actionData,\n bytes calldata\n ) external onlyIntegrationManager {\n (\n address stakingToken,\n bytes32 poolId,\n uint256 bptAmount,\n address[] memory expectedIncomingTokens,\n ,\n IBalancerV2Vault.PoolBalanceChange memory request\n ) = __decodeCombinedActionCallArgs(_actionData);\n\n __unstake(_vaultProxy, address(this), stakingToken, bptAmount);\n\n __redeem(_vaultProxy, poolId, bptAmount, expectedIncomingTokens, request);\n\n // The full amount of unstaked bpt might not be used in a redemption for exact underlyings\n // (with max bpt specified). In that case, re-stake the unused bpt.\n address bpt = __parseBalancerPoolAddress(poolId);\n uint256 remainingBpt = ERC20(bpt).balanceOf(address(this));\n if (remainingBpt > 0) {\n __stake(_vaultProxy, stakingToken, remainingBpt);\n }\n\n // The full amount of staked bpt will always have been used\n }\n\n // INTERNAL FUNCTIONS\n\n /// @dev Helper to perform all logic to LP on Balancer\n function __lend(\n address _recipient,\n bytes32 _poolId,\n address[] memory _spendAssets,\n uint256[] memory _spendAssetAmounts,\n IBalancerV2Vault.PoolBalanceChange memory _request\n ) internal {\n for (uint256 i; i < _spendAssets.length; i++) {\n __approveAssetMaxAsNeeded(\n _spendAssets[i],\n address(BALANCER_VAULT_CONTRACT),\n _spendAssetAmounts[i]\n );\n }\n\n __balancerV2Lend(_poolId, address(this), _recipient, _request);\n }\n\n /// @dev Helper to perform all logic to redeem Balancer BPTs\n function __redeem(\n address _vaultProxy,\n bytes32 _poolId,\n uint256 _spendBptAmount,\n address[] memory _expectedIncomingTokens,\n IBalancerV2Vault.PoolBalanceChange memory _request\n ) internal {\n __approveAssetMaxAsNeeded(\n __parseBalancerPoolAddress(_poolId),\n address(BALANCER_VAULT_CONTRACT),\n _spendBptAmount\n );\n\n // Since we are not parsing request.userData, we do not know with certainty which tokens\n // will be received. We are relying on the user-input _expectedIncomingTokens up to this point.\n // But, to guarantee that no unexpected tokens are received, we need to monitor those balances.\n uint256 unusedTokensCount = _request.assets.length - _expectedIncomingTokens.length;\n uint256[] memory preTxTokenBalancesIfUnused;\n if (unusedTokensCount > 0) {\n preTxTokenBalancesIfUnused = new uint256[](_request.assets.length);\n uint256 remainingCount = unusedTokensCount;\n for (uint256 i; remainingCount > 0; i++) {\n if (!_expectedIncomingTokens.contains(_request.assets[i])) {\n preTxTokenBalancesIfUnused[i] = ERC20(_request.assets[i]).balanceOf(\n _vaultProxy\n );\n remainingCount--;\n }\n }\n }\n\n __balancerV2Redeem(_poolId, address(this), payable(_vaultProxy), _request);\n\n if (unusedTokensCount > 0) {\n for (uint256 i; unusedTokensCount > 0; i++) {\n if (!_expectedIncomingTokens.contains(_request.assets[i])) {\n require(\n ERC20(_request.assets[i]).balanceOf(_vaultProxy) ==\n preTxTokenBalancesIfUnused[i],\n \"__balancerRedeem: Unexpected asset received\"\n );\n unusedTokensCount--;\n }\n }\n }\n }\n\n /////////////////////////////\n // PARSE ASSETS FOR METHOD //\n /////////////////////////////\n\n /// @notice Parses the expected assets to receive from a call on integration\n /// @param _selector The function selector for the callOnIntegration\n /// @param _actionData The encoded parameters for the callOnIntegration\n /// @return spendAssetsHandleType_ A type that dictates how to handle granting\n /// the adapter access to spend assets (`None` by default)\n /// @return spendAssets_ The assets to spend in the call\n /// @return spendAssetAmounts_ The max asset amounts to spend in the call\n /// @return incomingAssets_ The assets to receive in the call\n /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call\n function parseAssetsForAction(\n address,\n bytes4 _selector,\n bytes calldata _actionData\n )\n public\n view\n virtual\n override\n returns (\n IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,\n address[] memory spendAssets_,\n uint256[] memory spendAssetAmounts_,\n address[] memory incomingAssets_,\n uint256[] memory minIncomingAssetAmounts_\n )\n {\n if (_selector == CLAIM_REWARDS_SELECTOR) {\n return __parseAssetsForClaimRewards();\n } else if (_selector == LEND_AND_STAKE_SELECTOR) {\n return __parseAssetsForLendAndStake(_actionData);\n } else if (_selector == UNSTAKE_AND_REDEEM_SELECTOR) {\n return __parseAssetsForUnstakeAndRedeem(_actionData);\n } else if (_selector == STAKE_SELECTOR) {\n return __parseAssetsForStake(_actionData);\n } else if (_selector == UNSTAKE_SELECTOR) {\n return __parseAssetsForUnstake(_actionData);\n }\n\n revert(\"parseAssetsForAction: _selector invalid\");\n }\n\n /// @dev Helper function to parse spend and incoming assets from encoded call args\n /// during claimRewards() calls.\n /// No action required, all values empty.\n function __parseAssetsForClaimRewards()\n internal\n pure\n virtual\n returns (\n IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,\n address[] memory spendAssets_,\n uint256[] memory spendAssetAmounts_,\n address[] memory incomingAssets_,\n uint256[] memory minIncomingAssetAmounts_\n )\n {\n return (\n IIntegrationManager.SpendAssetsHandleType.None,\n new address[](0),\n new uint256[](0),\n new address[](0),\n new uint256[](0)\n );\n }\n\n /// @dev Helper function to parse spend and incoming assets from encoded call args\n /// during lend() calls\n function __parseAssetsForLendAndStake(bytes calldata _encodedCallArgs)\n internal\n view\n virtual\n returns (\n IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,\n address[] memory spendAssets_,\n uint256[] memory spendAssetAmounts_,\n address[] memory incomingAssets_,\n uint256[] memory minIncomingAssetAmounts_\n )\n {\n incomingAssets_ = new address[](1);\n minIncomingAssetAmounts_ = new uint256[](1);\n\n bytes32 poolId;\n address stakingToken;\n IBalancerV2Vault.PoolBalanceChange memory request;\n (\n stakingToken,\n poolId,\n minIncomingAssetAmounts_[0],\n spendAssets_,\n spendAssetAmounts_,\n request\n ) = __decodeCombinedActionCallArgs(_encodedCallArgs);\n\n __validatePoolForStakingToken(stakingToken, poolId);\n __validateNoInternalBalances(request.useInternalBalance);\n\n incomingAssets_[0] = stakingToken;\n\n return (\n IIntegrationManager.SpendAssetsHandleType.Transfer,\n spendAssets_,\n spendAssetAmounts_,\n incomingAssets_,\n minIncomingAssetAmounts_\n );\n }\n\n /// @dev Helper function to parse spend and incoming assets from encoded call args\n /// during stake() calls\n function __parseAssetsForStake(bytes calldata _encodedCallArgs)\n internal\n view\n virtual\n returns (\n IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,\n address[] memory spendAssets_,\n uint256[] memory spendAssetAmounts_,\n address[] memory incomingAssets_,\n uint256[] memory minIncomingAssetAmounts_\n )\n {\n (address stakingToken, uint256 bptAmount) = __decodeStakingActionCallArgs(\n _encodedCallArgs\n );\n\n spendAssets_ = new address[](1);\n spendAssetAmounts_ = new uint256[](1);\n incomingAssets_ = new address[](1);\n minIncomingAssetAmounts_ = new uint256[](1);\n\n spendAssets_[0] = __getBptForStakingToken(stakingToken);\n spendAssetAmounts_[0] = bptAmount;\n\n incomingAssets_[0] = stakingToken;\n minIncomingAssetAmounts_[0] = bptAmount;\n\n return (\n IIntegrationManager.SpendAssetsHandleType.Transfer,\n spendAssets_,\n spendAssetAmounts_,\n incomingAssets_,\n minIncomingAssetAmounts_\n );\n }\n\n /// @dev Helper function to parse spend and incoming assets from encoded call args\n /// during unstake() calls\n function __parseAssetsForUnstake(bytes calldata _encodedCallArgs)\n internal\n view\n virtual\n returns (\n IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,\n address[] memory spendAssets_,\n uint256[] memory spendAssetAmounts_,\n address[] memory incomingAssets_,\n uint256[] memory minIncomingAssetAmounts_\n )\n {\n (address stakingToken, uint256 bptAmount) = __decodeStakingActionCallArgs(\n _encodedCallArgs\n );\n\n spendAssets_ = new address[](1);\n spendAssetAmounts_ = new uint256[](1);\n incomingAssets_ = new address[](1);\n minIncomingAssetAmounts_ = new uint256[](1);\n\n spendAssets_[0] = stakingToken;\n spendAssetAmounts_[0] = bptAmount;\n\n incomingAssets_[0] = __getBptForStakingToken(stakingToken);\n minIncomingAssetAmounts_[0] = bptAmount;\n\n return (\n IIntegrationManager.SpendAssetsHandleType.Transfer,\n spendAssets_,\n spendAssetAmounts_,\n incomingAssets_,\n minIncomingAssetAmounts_\n );\n }\n\n /// @dev Helper function to parse spend and incoming assets from encoded call args\n /// during unstakeAndRedeem() calls\n function __parseAssetsForUnstakeAndRedeem(bytes calldata _encodedCallArgs)\n internal\n view\n virtual\n returns (\n IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,\n address[] memory spendAssets_,\n uint256[] memory spendAssetAmounts_,\n address[] memory incomingAssets_,\n uint256[] memory minIncomingAssetAmounts_\n )\n {\n spendAssets_ = new address[](1);\n spendAssetAmounts_ = new uint256[](1);\n\n bytes32 poolId;\n address stakingToken;\n IBalancerV2Vault.PoolBalanceChange memory request;\n (\n stakingToken,\n poolId,\n spendAssetAmounts_[0],\n incomingAssets_,\n minIncomingAssetAmounts_,\n request\n ) = __decodeCombinedActionCallArgs(_encodedCallArgs);\n\n __validatePoolForStakingToken(stakingToken, poolId);\n __validateNoInternalBalances(request.useInternalBalance);\n\n spendAssets_[0] = stakingToken;\n\n return (\n IIntegrationManager.SpendAssetsHandleType.Transfer,\n spendAssets_,\n spendAssetAmounts_,\n incomingAssets_,\n minIncomingAssetAmounts_\n );\n }\n\n /// @dev Helper to get a Balancer pool address (i.e., Balancer Pool Token) for a given id.\n /// See: https://github.com/balancer-labs/balancer-v2-monorepo/blob/42906226223f29e4489975eb3c0d5014dea83b66/pkg/vault/contracts/PoolRegistry.sol#L130-L139\n function __parseBalancerPoolAddress(bytes32 _poolId)\n internal\n pure\n returns (address poolAddress_)\n {\n return address(uint256(_poolId) >> (12 * 8));\n }\n\n /// @dev Helper to validate a given poolId for a given staking token.\n /// Does not validate the staking token itself, unless handled in the implementing contract\n /// during __getBptForStakingToken().\n function __validatePoolForStakingToken(address _stakingToken, bytes32 _poolId) internal view {\n require(\n __getBptForStakingToken(_stakingToken) == __parseBalancerPoolAddress(_poolId),\n \"__validateBptForStakingToken: Invalid\"\n );\n }\n\n /// @dev Helper to validate Balancer internal balances are not used\n function __validateNoInternalBalances(bool _useInternalBalances) internal pure {\n require(!_useInternalBalances, \"__validateNoInternalBalances: Invalid\");\n }\n\n //////////////\n // DECODERS //\n //////////////\n\n /// @dev Helper to decode callArgs for lend and redeem\n function __decodeCombinedActionCallArgs(bytes memory _encodedCallArgs)\n internal\n pure\n returns (\n address stakingToken_,\n bytes32 poolId_,\n uint256 bptAmount_,\n address[] memory usedTokens_, // only the assets that will actually be spent/received\n uint256[] memory usedTokenAmounts_, // only the assets that will actually be spent/received\n IBalancerV2Vault.PoolBalanceChange memory request_\n )\n {\n return\n abi.decode(\n _encodedCallArgs,\n (\n address,\n bytes32,\n uint256,\n address[],\n uint256[],\n IBalancerV2Vault.PoolBalanceChange\n )\n );\n }\n\n /// @dev Helper to decode the encoded call arguments for claiming rewards\n function __decodeClaimRewardsCallArgs(bytes memory _actionData)\n internal\n pure\n returns (address stakingToken_)\n {\n return abi.decode(_actionData, (address));\n }\n\n /// @dev Helper to decode callArgs for stake and unstake\n function __decodeStakingActionCallArgs(bytes memory _encodedCallArgs)\n internal\n pure\n returns (address stakingToken_, uint256 bptAmount_)\n {\n return abi.decode(_encodedCallArgs, (address, uint256));\n }\n}\n" }, "contracts/release/infrastructure/staking-wrappers/IStakingWrapper.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n\n (c) Enzyme Council \n\n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\n/// @title IStakingWrapper interface\n/// @author Enzyme Council \ninterface IStakingWrapper {\n struct TotalHarvestData {\n uint128 integral;\n uint128 lastCheckpointBalance;\n }\n\n struct UserHarvestData {\n uint128 integral;\n uint128 claimableReward;\n }\n\n function claimRewardsFor(address _for)\n external\n returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_);\n\n function deposit(uint256 _amount) external;\n\n function depositTo(address _to, uint256 _amount) external;\n\n function withdraw(uint256 _amount, bool _claimRewards)\n external\n returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_);\n\n function withdrawTo(\n address _to,\n uint256 _amount,\n bool _claimRewardsToHolder\n ) external;\n\n function withdrawToOnBehalf(\n address _onBehalf,\n address _to,\n uint256 _amount,\n bool _claimRewardsToHolder\n ) external;\n\n // STATE GETTERS\n\n function getRewardTokenAtIndex(uint256 _index) external view returns (address rewardToken_);\n\n function getRewardTokenCount() external view returns (uint256 count_);\n\n function getRewardTokens() external view returns (address[] memory rewardTokens_);\n\n function getTotalHarvestDataForRewardToken(address _rewardToken)\n external\n view\n returns (TotalHarvestData memory totalHarvestData_);\n\n function getUserHarvestDataForRewardToken(address _user, address _rewardToken)\n external\n view\n returns (UserHarvestData memory userHarvestData_);\n\n function isPaused() external view returns (bool isPaused_);\n}\n" }, "contracts/release/infrastructure/staking-wrappers/StakingWrapperBase.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n\n (c) Enzyme Council \n\n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\nimport \"../../utils/AddressArrayLib.sol\";\nimport \"./IStakingWrapper.sol\";\n\n/// @title StakingWrapperBase Contract\n/// @author Enzyme Council \n/// @notice A base contract for staking wrappers\n/// @dev Can be used as a base for both standard deployments and proxy targets.\n/// Draws on Convex's ConvexStakingWrapper implementation (https://github.com/convex-eth/platform/blob/main/contracts/contracts/wrappers/ConvexStakingWrapper.sol),\n/// which is based on Curve.fi gauge wrappers (https://github.com/curvefi/curve-dao-contracts/tree/master/contracts/gauges/wrappers)\nabstract contract StakingWrapperBase is IStakingWrapper, ERC20, ReentrancyGuard {\n using AddressArrayLib for address[];\n using SafeERC20 for ERC20;\n using SafeMath for uint256;\n\n event Deposited(address indexed from, address indexed to, uint256 amount);\n\n event PauseToggled(bool isPaused);\n\n event RewardsClaimed(\n address caller,\n address indexed user,\n address[] rewardTokens,\n uint256[] claimedAmounts\n );\n\n event RewardTokenAdded(address token);\n\n event TotalHarvestIntegralUpdated(address indexed rewardToken, uint256 integral);\n\n event TotalHarvestLastCheckpointBalanceUpdated(\n address indexed rewardToken,\n uint256 lastCheckpointBalance\n );\n\n event UserHarvestUpdated(\n address indexed user,\n address indexed rewardToken,\n uint256 integral,\n uint256 claimableReward\n );\n\n event Withdrawn(\n address indexed caller,\n address indexed from,\n address indexed to,\n uint256 amount\n );\n\n uint8 private constant DEFAULT_DECIMALS = 18;\n uint256 private constant INTEGRAL_PRECISION = 1e18;\n address internal immutable OWNER;\n\n // Paused stops new deposits and checkpoints\n bool private paused;\n address[] private rewardTokens;\n mapping(address => TotalHarvestData) private rewardTokenToTotalHarvestData;\n mapping(address => mapping(address => UserHarvestData)) private rewardTokenToUserToHarvestData;\n\n modifier onlyOwner() {\n require(msg.sender == OWNER, \"Only owner callable\");\n _;\n }\n\n constructor(\n address _owner,\n string memory _tokenName,\n string memory _tokenSymbol\n ) public ERC20(_tokenName, _tokenSymbol) {\n OWNER = _owner;\n }\n\n /// @notice Toggles pause for deposit and harvesting new rewards\n /// @param _isPaused True if next state is paused, false if unpaused\n function togglePause(bool _isPaused) external onlyOwner {\n paused = _isPaused;\n\n emit PauseToggled(_isPaused);\n }\n\n ////////////////////////////\n // DEPOSITOR INTERACTIONS //\n ////////////////////////////\n\n // CLAIM REWARDS\n\n /// @notice Claims all rewards for a given account\n /// @param _for The account for which to claim rewards\n /// @return rewardTokens_ The reward tokens\n /// @return claimedAmounts_ The reward token amounts claimed\n /// @dev Can be called off-chain to simulate the total harvestable rewards for a particular user\n function claimRewardsFor(address _for)\n external\n override\n nonReentrant\n returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_)\n {\n return __checkpointAndClaim(_for);\n }\n\n // DEPOSIT\n\n /// @notice Deposits tokens to be staked, minting staking token to sender\n /// @param _amount The amount of tokens to deposit\n function deposit(uint256 _amount) external override {\n __deposit(msg.sender, msg.sender, _amount);\n }\n\n /// @notice Deposits tokens to be staked, minting staking token to a specified account\n /// @param _to The account to receive staking tokens\n /// @param _amount The amount of tokens to deposit\n function depositTo(address _to, uint256 _amount) external override {\n __deposit(msg.sender, _to, _amount);\n }\n\n /// @dev Helper to deposit tokens to be staked\n function __deposit(\n address _from,\n address _to,\n uint256 _amount\n ) private nonReentrant {\n require(!isPaused(), \"__deposit: Paused\");\n\n // Checkpoint before minting\n __checkpoint([_to, address(0)]);\n _mint(_to, _amount);\n\n __depositLogic(_from, _amount);\n\n emit Deposited(_from, _to, _amount);\n }\n\n // WITHDRAWAL\n\n /// @notice Withdraws staked tokens, returning tokens to the sender, and optionally claiming rewards\n /// @param _amount The amount of tokens to withdraw\n /// @param _claimRewards True if accrued rewards should be claimed\n /// @return rewardTokens_ The reward tokens\n /// @return claimedAmounts_ The reward token amounts claimed\n /// @dev Setting `_claimRewards` to true will save gas over separate calls to withdraw + claim\n function withdraw(uint256 _amount, bool _claimRewards)\n external\n override\n returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_)\n {\n return __withdraw(msg.sender, msg.sender, _amount, _claimRewards);\n }\n\n /// @notice Withdraws staked tokens, returning tokens to a specified account,\n /// and optionally claims rewards to the staked token holder\n /// @param _to The account to receive tokens\n /// @param _amount The amount of tokens to withdraw\n function withdrawTo(\n address _to,\n uint256 _amount,\n bool _claimRewardsToHolder\n ) external override {\n __withdraw(msg.sender, _to, _amount, _claimRewardsToHolder);\n }\n\n /// @notice Withdraws staked tokens on behalf of AccountA, returning tokens to a specified AccountB,\n /// and optionally claims rewards to the staked token holder\n /// @param _onBehalf The account on behalf to withdraw\n /// @param _to The account to receive tokens\n /// @param _amount The amount of tokens to withdraw\n /// @dev The caller must have an adequate ERC20.allowance() for _onBehalf\n function withdrawToOnBehalf(\n address _onBehalf,\n address _to,\n uint256 _amount,\n bool _claimRewardsToHolder\n ) external override {\n // Validate and reduce sender approval\n _approve(_onBehalf, msg.sender, allowance(_onBehalf, msg.sender).sub(_amount));\n\n __withdraw(_onBehalf, _to, _amount, _claimRewardsToHolder);\n }\n\n /// @dev Helper to withdraw staked tokens\n function __withdraw(\n address _from,\n address _to,\n uint256 _amount,\n bool _claimRewards\n )\n private\n nonReentrant\n returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_)\n {\n // Checkpoint before burning\n if (_claimRewards) {\n (rewardTokens_, claimedAmounts_) = __checkpointAndClaim(_from);\n } else {\n __checkpoint([_from, address(0)]);\n }\n\n _burn(_from, _amount);\n\n __withdrawLogic(_to, _amount);\n\n emit Withdrawn(msg.sender, _from, _to, _amount);\n\n return (rewardTokens_, claimedAmounts_);\n }\n\n /////////////\n // REWARDS //\n /////////////\n\n // Rewards tokens are added by the inheriting contract. Rewards tokens should be added, but not removed.\n // If new rewards tokens need to be added over time, that logic must be handled by the inheriting contract,\n // and can make use of __harvestRewardsLogic() if necessary\n\n // INTERNAL FUNCTIONS\n\n /// @dev Helper to add new reward tokens. Silently ignores duplicates.\n function __addRewardToken(address _rewardToken) internal {\n if (!rewardTokens.contains(_rewardToken)) {\n rewardTokens.push(_rewardToken);\n\n emit RewardTokenAdded(_rewardToken);\n }\n }\n\n // PRIVATE FUNCTIONS\n\n /// @dev Helper to calculate an unaccounted for reward amount due to a user based on integral values\n function __calcClaimableRewardForIntegralDiff(\n address _account,\n uint256 _totalHarvestIntegral,\n uint256 _userHarvestIntegral\n ) private view returns (uint256 claimableReward_) {\n return\n balanceOf(_account).mul(_totalHarvestIntegral.sub(_userHarvestIntegral)).div(\n INTEGRAL_PRECISION\n );\n }\n\n /// @dev Helper to calculate an unaccounted for integral amount based on checkpoint balance diff\n function __calcIntegralForBalDiff(\n uint256 _supply,\n uint256 _currentBalance,\n uint256 _lastCheckpointBalance\n ) private pure returns (uint256 integral_) {\n if (_supply > 0) {\n uint256 balDiff = _currentBalance.sub(_lastCheckpointBalance);\n if (balDiff > 0) {\n return balDiff.mul(INTEGRAL_PRECISION).div(_supply);\n }\n }\n\n return 0;\n }\n\n /// @dev Helper to checkpoint harvest data for specified accounts.\n /// Harvests all rewards prior to checkpoint.\n function __checkpoint(address[2] memory _accounts) private {\n // If paused, continue to checkpoint, but don't attempt to get new rewards\n if (!isPaused()) {\n __harvestRewardsLogic();\n }\n\n uint256 supply = totalSupply();\n\n uint256 rewardTokensLength = rewardTokens.length;\n for (uint256 i; i < rewardTokensLength; i++) {\n __updateHarvest(rewardTokens[i], _accounts, supply);\n }\n }\n\n /// @dev Helper to checkpoint harvest data for specified accounts.\n /// Harvests all rewards prior to checkpoint.\n function __checkpointAndClaim(address _account)\n private\n returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_)\n {\n // If paused, continue to checkpoint, but don't attempt to get new rewards\n if (!isPaused()) {\n __harvestRewardsLogic();\n }\n\n uint256 supply = totalSupply();\n\n rewardTokens_ = rewardTokens;\n claimedAmounts_ = new uint256[](rewardTokens_.length);\n for (uint256 i; i < rewardTokens_.length; i++) {\n claimedAmounts_[i] = __updateHarvestAndClaim(rewardTokens_[i], _account, supply);\n }\n\n emit RewardsClaimed(msg.sender, _account, rewardTokens_, claimedAmounts_);\n\n return (rewardTokens_, claimedAmounts_);\n }\n\n /// @dev Helper to update harvest data\n function __updateHarvest(\n address _rewardToken,\n address[2] memory _accounts,\n uint256 _supply\n ) private {\n TotalHarvestData storage totalHarvestData = rewardTokenToTotalHarvestData[_rewardToken];\n\n uint256 totalIntegral = totalHarvestData.integral;\n uint256 bal = ERC20(_rewardToken).balanceOf(address(this));\n uint256 integralToAdd = __calcIntegralForBalDiff(\n _supply,\n bal,\n totalHarvestData.lastCheckpointBalance\n );\n if (integralToAdd > 0) {\n totalIntegral = totalIntegral.add(integralToAdd);\n totalHarvestData.integral = uint128(totalIntegral);\n emit TotalHarvestIntegralUpdated(_rewardToken, totalIntegral);\n\n totalHarvestData.lastCheckpointBalance = uint128(bal);\n emit TotalHarvestLastCheckpointBalanceUpdated(_rewardToken, bal);\n }\n\n for (uint256 i; i < _accounts.length; i++) {\n // skip address(0), passed in upon mint and burn\n if (_accounts[i] == address(0)) continue;\n\n UserHarvestData storage userHarvestData = rewardTokenToUserToHarvestData[_rewardToken][\n _accounts[i]\n ];\n\n uint256 userIntegral = userHarvestData.integral;\n if (userIntegral < totalIntegral) {\n uint256 claimableReward = uint256(userHarvestData.claimableReward).add(\n __calcClaimableRewardForIntegralDiff(_accounts[i], totalIntegral, userIntegral)\n );\n\n userHarvestData.claimableReward = uint128(claimableReward);\n userHarvestData.integral = uint128(totalIntegral);\n\n emit UserHarvestUpdated(\n _accounts[i],\n _rewardToken,\n totalIntegral,\n claimableReward\n );\n }\n }\n }\n\n /// @dev Helper to update harvest data and claim all rewards to holder\n function __updateHarvestAndClaim(\n address _rewardToken,\n address _account,\n uint256 _supply\n ) private returns (uint256 claimedAmount_) {\n TotalHarvestData storage totalHarvestData = rewardTokenToTotalHarvestData[_rewardToken];\n\n uint256 totalIntegral = totalHarvestData.integral;\n uint256 integralToAdd = __calcIntegralForBalDiff(\n _supply,\n ERC20(_rewardToken).balanceOf(address(this)),\n totalHarvestData.lastCheckpointBalance\n );\n if (integralToAdd > 0) {\n totalIntegral = totalIntegral.add(integralToAdd);\n totalHarvestData.integral = uint128(totalIntegral);\n\n emit TotalHarvestIntegralUpdated(_rewardToken, totalIntegral);\n }\n\n UserHarvestData storage userHarvestData = rewardTokenToUserToHarvestData[_rewardToken][\n _account\n ];\n\n uint256 userIntegral = userHarvestData.integral;\n claimedAmount_ = userHarvestData.claimableReward;\n if (userIntegral < totalIntegral) {\n userHarvestData.integral = uint128(totalIntegral);\n claimedAmount_ = claimedAmount_.add(\n __calcClaimableRewardForIntegralDiff(_account, totalIntegral, userIntegral)\n );\n\n emit UserHarvestUpdated(_account, _rewardToken, totalIntegral, claimedAmount_);\n }\n\n if (claimedAmount_ > 0) {\n userHarvestData.claimableReward = 0;\n ERC20(_rewardToken).safeTransfer(_account, claimedAmount_);\n\n emit UserHarvestUpdated(_account, _rewardToken, totalIntegral, 0);\n }\n\n // Repeat balance lookup since the reward token could have irregular transfer behavior\n uint256 finalBal = ERC20(_rewardToken).balanceOf(address(this));\n if (finalBal < totalHarvestData.lastCheckpointBalance) {\n totalHarvestData.lastCheckpointBalance = uint128(finalBal);\n\n emit TotalHarvestLastCheckpointBalanceUpdated(_rewardToken, finalBal);\n }\n\n return claimedAmount_;\n }\n\n ////////////////////////////////\n // REQUIRED VIRTUAL FUNCTIONS //\n ////////////////////////////////\n\n /// @dev Logic to be run during a deposit, specific to the integrated protocol.\n /// Do not mint staking tokens, which already happens during __deposit().\n function __depositLogic(address _onBehalf, uint256 _amount) internal virtual;\n\n /// @dev Logic to be run during a checkpoint to harvest new rewards, specific to the integrated protocol.\n /// Can also be used to add new rewards tokens dynamically.\n /// Do not checkpoint, only harvest the rewards.\n function __harvestRewardsLogic() internal virtual;\n\n /// @dev Logic to be run during a withdrawal, specific to the integrated protocol.\n /// Do not burn staking tokens, which already happens during __withdraw().\n function __withdrawLogic(address _to, uint256 _amount) internal virtual;\n\n /////////////////////\n // ERC20 OVERRIDES //\n /////////////////////\n\n /// @notice Gets the token decimals\n /// @return decimals_ The token decimals\n /// @dev Implementing contracts should override to set different decimals\n function decimals() public view virtual override returns (uint8 decimals_) {\n return DEFAULT_DECIMALS;\n }\n\n /// @dev Overrides ERC20._transfer() in order to checkpoint sender and recipient pre-transfer rewards\n function _transfer(\n address _from,\n address _to,\n uint256 _amount\n ) internal override nonReentrant {\n __checkpoint([_from, _to]);\n super._transfer(_from, _to, _amount);\n }\n\n ///////////////////\n // STATE GETTERS //\n ///////////////////\n\n /// @notice Gets the reward token at a particular index\n /// @return rewardToken_ The reward token address\n function getRewardTokenAtIndex(uint256 _index)\n public\n view\n override\n returns (address rewardToken_)\n {\n return rewardTokens[_index];\n }\n\n /// @notice Gets the count of reward tokens being harvested\n /// @return count_ The count\n function getRewardTokenCount() public view override returns (uint256 count_) {\n return rewardTokens.length;\n }\n\n /// @notice Gets all reward tokens being harvested\n /// @return rewardTokens_ The reward tokens\n function getRewardTokens() public view override returns (address[] memory rewardTokens_) {\n return rewardTokens;\n }\n\n /// @notice Gets the TotalHarvestData for a specified reward token\n /// @param _rewardToken The reward token\n /// @return totalHarvestData_ The TotalHarvestData\n function getTotalHarvestDataForRewardToken(address _rewardToken)\n public\n view\n override\n returns (TotalHarvestData memory totalHarvestData_)\n {\n return rewardTokenToTotalHarvestData[_rewardToken];\n }\n\n /// @notice Gets the UserHarvestData for a specified account and reward token\n /// @param _user The account\n /// @param _rewardToken The reward token\n /// @return userHarvestData_ The UserHarvestData\n function getUserHarvestDataForRewardToken(address _user, address _rewardToken)\n public\n view\n override\n returns (UserHarvestData memory userHarvestData_)\n {\n return rewardTokenToUserToHarvestData[_rewardToken][_user];\n }\n\n /// @notice Checks if deposits and new reward harvesting are paused\n /// @return isPaused_ True if paused\n function isPaused() public view override returns (bool isPaused_) {\n return paused;\n }\n}\n" }, "contracts/release/infrastructure/staking-wrappers/StakingWrapperLibBase.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n\n (c) Enzyme Council \n\n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\n\nimport \"./StakingWrapperBase.sol\";\n\n/// @title StakingWrapperLibBase Contract\n/// @author Enzyme Council \n/// @notice A staking wrapper base for proxy targets, extending StakingWrapperBase\nabstract contract StakingWrapperLibBase is StakingWrapperBase {\n event TokenNameSet(string name);\n\n event TokenSymbolSet(string symbol);\n\n string private tokenName;\n string private tokenSymbol;\n\n /// @dev Helper function to set token name\n function __setTokenName(string memory _name) internal {\n tokenName = _name;\n\n emit TokenNameSet(_name);\n }\n\n /// @dev Helper function to set token symbol\n function __setTokenSymbol(string memory _symbol) internal {\n tokenSymbol = _symbol;\n\n emit TokenSymbolSet(_symbol);\n }\n\n /////////////////////\n // ERC20 OVERRIDES //\n /////////////////////\n\n /// @notice Gets the token name\n /// @return name_ The token name\n /// @dev Overrides the constructor-set storage for use in proxies\n function name() public view override returns (string memory name_) {\n return tokenName;\n }\n\n /// @notice Gets the token symbol\n /// @return symbol_ The token symbol\n /// @dev Overrides the constructor-set storage for use in proxies\n function symbol() public view override returns (string memory symbol_) {\n return tokenSymbol;\n }\n}\n" }, "contracts/release/infrastructure/staking-wrappers/aura-balancer-v2-lp/AuraBalancerV2LpStakingWrapperFactory.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n (c) Enzyme Council \n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"../convex-curve-lp/ConvexCurveLpStakingWrapperFactory.sol\";\n\n/// @title AuraBalancerV2LpStakingWrapperFactory Contract\n/// @author Enzyme Council \n/// @notice A contract factory for Aura BalancerV2 staking wrapper instances\ncontract AuraBalancerV2LpStakingWrapperFactory is ConvexCurveLpStakingWrapperFactory {\n constructor(\n address _dispatcher,\n address _auraBooster,\n address _balToken,\n address _auraToken\n )\n public\n ConvexCurveLpStakingWrapperFactory(_dispatcher, _auraBooster, _balToken, _auraToken)\n {}\n}\n" }, "contracts/release/infrastructure/staking-wrappers/convex-curve-lp/ConvexCurveLpStakingWrapperFactory.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n (c) Enzyme Council \n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"../../../../persistent/dispatcher/IDispatcher.sol\";\nimport \"../../../utils/beacon-proxy/BeaconProxyFactory.sol\";\nimport \"./ConvexCurveLpStakingWrapperLib.sol\";\n\n/// @title ConvexCurveLpStakingWrapperFactory Contract\n/// @author Enzyme Council \n/// @notice A contract factory for ConvexCurveLpStakingWrapper instances\ncontract ConvexCurveLpStakingWrapperFactory is BeaconProxyFactory {\n event WrapperDeployed(uint256 indexed pid, address wrapperProxy, address curveLpToken);\n\n IDispatcher private immutable DISPATCHER_CONTRACT;\n\n mapping(uint256 => address) private pidToWrapper;\n // Handy cache for interacting contracts\n mapping(address => address) private wrapperToCurveLpToken;\n\n modifier onlyOwner() {\n require(msg.sender == getOwner(), \"Only the owner can call this function\");\n _;\n }\n\n constructor(\n address _dispatcher,\n address _convexBooster,\n address _crvToken,\n address _cvxToken\n ) public BeaconProxyFactory(address(0)) {\n DISPATCHER_CONTRACT = IDispatcher(_dispatcher);\n\n __setCanonicalLib(\n address(\n new ConvexCurveLpStakingWrapperLib(\n address(this),\n _convexBooster,\n _crvToken,\n _cvxToken\n )\n )\n );\n }\n\n /// @notice Deploys a staking wrapper for a given Convex pool\n /// @param _pid The Convex Curve pool id\n /// @return wrapperProxy_ The staking wrapper proxy contract address\n function deploy(uint256 _pid) external returns (address wrapperProxy_) {\n require(getWrapperForConvexPool(_pid) == address(0), \"deploy: Wrapper already exists\");\n\n bytes memory constructData = abi.encodeWithSelector(\n ConvexCurveLpStakingWrapperLib.init.selector,\n _pid\n );\n\n wrapperProxy_ = deployProxy(constructData);\n\n pidToWrapper[_pid] = wrapperProxy_;\n\n address lpToken = ConvexCurveLpStakingWrapperLib(wrapperProxy_).getCurveLpToken();\n wrapperToCurveLpToken[wrapperProxy_] = lpToken;\n\n emit WrapperDeployed(_pid, wrapperProxy_, lpToken);\n\n return wrapperProxy_;\n }\n\n /// @notice Pause deposits and harvesting new rewards for the given wrappers\n /// @param _wrappers The wrappers to pause\n function pauseWrappers(address[] calldata _wrappers) external onlyOwner {\n for (uint256 i; i < _wrappers.length; i++) {\n ConvexCurveLpStakingWrapperLib(_wrappers[i]).togglePause(true);\n }\n }\n\n /// @notice Unpauses deposits and harvesting new rewards for the given wrappers\n /// @param _wrappers The wrappers to unpause\n function unpauseWrappers(address[] calldata _wrappers) external onlyOwner {\n for (uint256 i; i < _wrappers.length; i++) {\n ConvexCurveLpStakingWrapperLib(_wrappers[i]).togglePause(false);\n }\n }\n\n ////////////////////////////////////\n // BEACON PROXY FACTORY OVERRIDES //\n ////////////////////////////////////\n\n /// @notice Gets the contract owner\n /// @return owner_ The contract owner\n function getOwner() public view override returns (address owner_) {\n return DISPATCHER_CONTRACT.getOwner();\n }\n\n ///////////////////\n // STATE GETTERS //\n ///////////////////\n\n // EXTERNAL FUNCTIONS\n\n /// @notice Gets the Curve LP token address for a given wrapper\n /// @param _wrapper The wrapper proxy address\n /// @return lpToken_ The Curve LP token address\n function getCurveLpTokenForWrapper(address _wrapper) external view returns (address lpToken_) {\n return wrapperToCurveLpToken[_wrapper];\n }\n\n // PUBLIC FUNCTIONS\n\n /// @notice Gets the wrapper address for a given Convex pool\n /// @param _pid The Convex pool id\n /// @return wrapper_ The wrapper proxy address\n function getWrapperForConvexPool(uint256 _pid) public view returns (address wrapper_) {\n return pidToWrapper[_pid];\n }\n}\n" }, "contracts/release/infrastructure/staking-wrappers/convex-curve-lp/ConvexCurveLpStakingWrapperLib.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n\n (c) Enzyme Council \n\n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"../../../interfaces/IConvexBaseRewardPool.sol\";\nimport \"../../../interfaces/IConvexBooster.sol\";\nimport \"../../../interfaces/IConvexVirtualBalanceRewardPool.sol\";\nimport \"../StakingWrapperLibBase.sol\";\n\n/// @title ConvexCurveLpStakingWrapperLib Contract\n/// @author Enzyme Council \n/// @notice A library contract for ConvexCurveLpStakingWrapper instances\ncontract ConvexCurveLpStakingWrapperLib is StakingWrapperLibBase {\n IConvexBooster private immutable CONVEX_BOOSTER_CONTRACT;\n address private immutable CRV_TOKEN;\n address private immutable CVX_TOKEN;\n\n address private convexPool;\n uint256 private convexPoolId;\n address private curveLPToken;\n\n constructor(\n address _owner,\n address _convexBooster,\n address _crvToken,\n address _cvxToken\n ) public StakingWrapperBase(_owner, \"\", \"\") {\n CONVEX_BOOSTER_CONTRACT = IConvexBooster(_convexBooster);\n CRV_TOKEN = _crvToken;\n CVX_TOKEN = _cvxToken;\n }\n\n /// @notice Initializes the proxy\n /// @param _pid The Convex pool id for which to use the proxy\n function init(uint256 _pid) external {\n // Can validate with any variable set here\n require(getCurveLpToken() == address(0), \"init: Initialized\");\n\n IConvexBooster.PoolInfo memory poolInfo = CONVEX_BOOSTER_CONTRACT.poolInfo(_pid);\n\n // Set ERC20 info on proxy\n __setTokenName(string(abi.encodePacked(\"Enzyme Staked: \", ERC20(poolInfo.token).name())));\n __setTokenSymbol(string(abi.encodePacked(\"stk\", ERC20(poolInfo.token).symbol())));\n\n curveLPToken = poolInfo.lptoken;\n convexPool = poolInfo.crvRewards;\n convexPoolId = _pid;\n\n __addRewardToken(CRV_TOKEN);\n __addRewardToken(CVX_TOKEN);\n addExtraRewards();\n\n setApprovals();\n }\n\n /// @notice Adds rewards tokens that have not yet been added to the wrapper\n /// @dev Anybody can call, in case more pool tokens are added.\n /// Is called prior to every new harvest.\n function addExtraRewards() public {\n IConvexBaseRewardPool convexPoolContract = IConvexBaseRewardPool(getConvexPool());\n // Could probably exit early after validating that extraRewardsCount + 2 <= rewardsTokens.length,\n // but this protects against a reward token being removed that still needs to be paid out\n uint256 extraRewardsCount = convexPoolContract.extraRewardsLength();\n for (uint256 i; i < extraRewardsCount; i++) {\n // __addRewardToken silently ignores duplicates\n __addRewardToken(\n IConvexVirtualBalanceRewardPool(convexPoolContract.extraRewards(i)).rewardToken()\n );\n }\n }\n\n /// @notice Sets necessary ERC20 approvals, as-needed\n function setApprovals() public {\n ERC20(getCurveLpToken()).safeApprove(address(CONVEX_BOOSTER_CONTRACT), type(uint256).max);\n }\n\n ////////////////////////////////\n // STAKING WRAPPER BASE LOGIC //\n ////////////////////////////////\n\n /// @dev Logic to be run during a deposit, specific to the integrated protocol.\n /// Do not mint staking tokens, which already happens during __deposit().\n function __depositLogic(address _from, uint256 _amount) internal override {\n ERC20(getCurveLpToken()).safeTransferFrom(_from, address(this), _amount);\n CONVEX_BOOSTER_CONTRACT.deposit(convexPoolId, _amount, true);\n }\n\n /// @dev Logic to be run during a checkpoint to harvest new rewards, specific to the integrated protocol.\n /// Can also be used to add new rewards tokens dynamically.\n /// Do not checkpoint, only harvest the rewards.\n function __harvestRewardsLogic() internal override {\n // It's probably overly-cautious to check rewards on every call,\n // but even when the pool has 1 extra reward token (most have 0) it only adds ~10-15k gas units,\n // so more convenient to always check than to monitor for rewards changes.\n addExtraRewards();\n IConvexBaseRewardPool(getConvexPool()).getReward();\n }\n\n /// @dev Logic to be run during a withdrawal, specific to the integrated protocol.\n /// Do not burn staking tokens, which already happens during __withdraw().\n function __withdrawLogic(address _to, uint256 _amount) internal override {\n IConvexBaseRewardPool(getConvexPool()).withdrawAndUnwrap(_amount, false);\n ERC20(getCurveLpToken()).safeTransfer(_to, _amount);\n }\n\n ///////////////////\n // STATE GETTERS //\n ///////////////////\n\n /// @notice Gets the associated Convex reward pool address\n /// @return convexPool_ The reward pool\n function getConvexPool() public view returns (address convexPool_) {\n return convexPool;\n }\n\n /// @notice Gets the associated Convex reward pool id (pid)\n /// @return convexPoolId_ The pid\n function getConvexPoolId() public view returns (uint256 convexPoolId_) {\n return convexPoolId;\n }\n\n /// @notice Gets the associated Curve LP token\n /// @return curveLPToken_ The Curve LP token\n function getCurveLpToken() public view returns (address curveLPToken_) {\n return curveLPToken;\n }\n}\n" }, "contracts/release/interfaces/IBalancerV2Vault.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n (c) Enzyme Council \n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\n/// @title IBalancerV2Vault interface\n/// @author Enzyme Council \ninterface IBalancerV2Vault {\n // JoinPoolRequest and ExitPoolRequest are just differently labeled versions of PoolBalanceChange.\n // See: https://github.com/balancer-labs/balancer-v2-monorepo/blob/42906226223f29e4489975eb3c0d5014dea83b66/pkg/vault/contracts/PoolBalances.sol#L70\n struct PoolBalanceChange {\n address[] assets;\n uint256[] limits;\n bytes userData;\n bool useInternalBalance;\n }\n\n function exitPool(\n bytes32 _poolId,\n address _sender,\n address payable _recipient,\n PoolBalanceChange memory _request\n ) external;\n\n function getPoolTokens(bytes32 _poolId)\n external\n view\n returns (\n address[] memory tokens_,\n uint256[] memory balances_,\n uint256 lastChangeBlock_\n );\n\n function joinPool(\n bytes32 _poolId,\n address _sender,\n address _recipient,\n PoolBalanceChange memory _request\n ) external payable;\n\n function setRelayerApproval(\n address _sender,\n address _relayer,\n bool _approved\n ) external;\n}\n" }, "contracts/release/interfaces/IConvexBaseRewardPool.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n (c) Enzyme Council \n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\n\n/// @title IConvexBaseRewardPool Interface\n/// @author Enzyme Council \ninterface IConvexBaseRewardPool {\n function balanceOf(address) external view returns (uint256);\n\n function extraRewards(uint256) external view returns (address);\n\n function extraRewardsLength() external view returns (uint256);\n\n function getReward() external returns (bool);\n\n function withdraw(uint256, bool) external;\n\n function withdrawAndUnwrap(uint256, bool) external returns (bool);\n}\n" }, "contracts/release/interfaces/IConvexBooster.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n (c) Enzyme Council \n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\n/// @title IConvexBooster Interface\n/// @author Enzyme Council \ninterface IConvexBooster {\n struct PoolInfo {\n address lptoken;\n address token;\n address gauge;\n address crvRewards;\n address stash;\n bool shutdown;\n }\n\n function deposit(\n uint256,\n uint256,\n bool\n ) external returns (bool);\n\n function poolInfo(uint256) external view returns (PoolInfo memory);\n}\n" }, "contracts/release/interfaces/IConvexVirtualBalanceRewardPool.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n (c) Enzyme Council \n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\n\n/// @title IConvexVirtualBalanceRewardPool Interface\n/// @author Enzyme Council \ninterface IConvexVirtualBalanceRewardPool {\n function rewardToken() external view returns (address);\n}\n" }, "contracts/release/utils/AddressArrayLib.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n\n (c) Enzyme Council \n\n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\n\n/// @title AddressArray Library\n/// @author Enzyme Council \n/// @notice A library to extend the address array data type\nlibrary AddressArrayLib {\n /////////////\n // STORAGE //\n /////////////\n\n /// @dev Helper to remove an item from a storage array\n function removeStorageItem(address[] storage _self, address _itemToRemove)\n internal\n returns (bool removed_)\n {\n uint256 itemCount = _self.length;\n for (uint256 i; i < itemCount; i++) {\n if (_self[i] == _itemToRemove) {\n if (i < itemCount - 1) {\n _self[i] = _self[itemCount - 1];\n }\n _self.pop();\n removed_ = true;\n break;\n }\n }\n\n return removed_;\n }\n\n /// @dev Helper to verify if a storage array contains a particular value\n function storageArrayContains(address[] storage _self, address _target)\n internal\n view\n returns (bool doesContain_)\n {\n uint256 arrLength = _self.length;\n for (uint256 i; i < arrLength; i++) {\n if (_target == _self[i]) {\n return true;\n }\n }\n return false;\n }\n\n ////////////\n // MEMORY //\n ////////////\n\n /// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.\n function addItem(address[] memory _self, address _itemToAdd)\n internal\n pure\n returns (address[] memory nextArray_)\n {\n nextArray_ = new address[](_self.length + 1);\n for (uint256 i; i < _self.length; i++) {\n nextArray_[i] = _self[i];\n }\n nextArray_[_self.length] = _itemToAdd;\n\n return nextArray_;\n }\n\n /// @dev Helper to add an item to an array, only if it is not already in the array.\n function addUniqueItem(address[] memory _self, address _itemToAdd)\n internal\n pure\n returns (address[] memory nextArray_)\n {\n if (contains(_self, _itemToAdd)) {\n return _self;\n }\n\n return addItem(_self, _itemToAdd);\n }\n\n /// @dev Helper to verify if an array contains a particular value\n function contains(address[] memory _self, address _target)\n internal\n pure\n returns (bool doesContain_)\n {\n for (uint256 i; i < _self.length; i++) {\n if (_target == _self[i]) {\n return true;\n }\n }\n return false;\n }\n\n /// @dev Helper to merge the unique items of a second array.\n /// Does not consider uniqueness of either array, only relative uniqueness.\n /// Preserves ordering.\n function mergeArray(address[] memory _self, address[] memory _arrayToMerge)\n internal\n pure\n returns (address[] memory nextArray_)\n {\n uint256 newUniqueItemCount;\n for (uint256 i; i < _arrayToMerge.length; i++) {\n if (!contains(_self, _arrayToMerge[i])) {\n newUniqueItemCount++;\n }\n }\n\n if (newUniqueItemCount == 0) {\n return _self;\n }\n\n nextArray_ = new address[](_self.length + newUniqueItemCount);\n for (uint256 i; i < _self.length; i++) {\n nextArray_[i] = _self[i];\n }\n uint256 nextArrayIndex = _self.length;\n for (uint256 i; i < _arrayToMerge.length; i++) {\n if (!contains(_self, _arrayToMerge[i])) {\n nextArray_[nextArrayIndex] = _arrayToMerge[i];\n nextArrayIndex++;\n }\n }\n\n return nextArray_;\n }\n\n /// @dev Helper to verify if array is a set of unique values.\n /// Does not assert length > 0.\n function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {\n if (_self.length <= 1) {\n return true;\n }\n\n uint256 arrayLength = _self.length;\n for (uint256 i; i < arrayLength; i++) {\n for (uint256 j = i + 1; j < arrayLength; j++) {\n if (_self[i] == _self[j]) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n /// @dev Helper to remove items from an array. Removes all matching occurrences of each item.\n /// Does not assert uniqueness of either array.\n function removeItems(address[] memory _self, address[] memory _itemsToRemove)\n internal\n pure\n returns (address[] memory nextArray_)\n {\n if (_itemsToRemove.length == 0) {\n return _self;\n }\n\n bool[] memory indexesToRemove = new bool[](_self.length);\n uint256 remainingItemsCount = _self.length;\n for (uint256 i; i < _self.length; i++) {\n if (contains(_itemsToRemove, _self[i])) {\n indexesToRemove[i] = true;\n remainingItemsCount--;\n }\n }\n\n if (remainingItemsCount == _self.length) {\n nextArray_ = _self;\n } else if (remainingItemsCount > 0) {\n nextArray_ = new address[](remainingItemsCount);\n uint256 nextArrayIndex;\n for (uint256 i; i < _self.length; i++) {\n if (!indexesToRemove[i]) {\n nextArray_[nextArrayIndex] = _self[i];\n nextArrayIndex++;\n }\n }\n }\n\n return nextArray_;\n }\n}\n" }, "contracts/release/utils/AssetHelpers.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n\n (c) Enzyme Council \n\n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/SafeERC20.sol\";\n\n/// @title AssetHelpers Contract\n/// @author Enzyme Council \n/// @notice A util contract for common token actions\nabstract contract AssetHelpers {\n using SafeERC20 for ERC20;\n using SafeMath for uint256;\n\n /// @dev Helper to aggregate amounts of the same assets\n function __aggregateAssetAmounts(address[] memory _rawAssets, uint256[] memory _rawAmounts)\n internal\n pure\n returns (address[] memory aggregatedAssets_, uint256[] memory aggregatedAmounts_)\n {\n if (_rawAssets.length == 0) {\n return (aggregatedAssets_, aggregatedAmounts_);\n }\n\n uint256 aggregatedAssetCount = 1;\n for (uint256 i = 1; i < _rawAssets.length; i++) {\n bool contains;\n for (uint256 j; j < i; j++) {\n if (_rawAssets[i] == _rawAssets[j]) {\n contains = true;\n break;\n }\n }\n if (!contains) {\n aggregatedAssetCount++;\n }\n }\n\n aggregatedAssets_ = new address[](aggregatedAssetCount);\n aggregatedAmounts_ = new uint256[](aggregatedAssetCount);\n uint256 aggregatedAssetIndex;\n for (uint256 i; i < _rawAssets.length; i++) {\n bool contains;\n for (uint256 j; j < aggregatedAssetIndex; j++) {\n if (_rawAssets[i] == aggregatedAssets_[j]) {\n contains = true;\n\n aggregatedAmounts_[j] += _rawAmounts[i];\n\n break;\n }\n }\n if (!contains) {\n aggregatedAssets_[aggregatedAssetIndex] = _rawAssets[i];\n aggregatedAmounts_[aggregatedAssetIndex] = _rawAmounts[i];\n aggregatedAssetIndex++;\n }\n }\n\n return (aggregatedAssets_, aggregatedAmounts_);\n }\n\n /// @dev Helper to approve a target account with the max amount of an asset.\n /// This is helpful for fully trusted contracts, such as adapters that\n /// interact with external protocol like Uniswap, Compound, etc.\n function __approveAssetMaxAsNeeded(\n address _asset,\n address _target,\n uint256 _neededAmount\n ) internal {\n uint256 allowance = ERC20(_asset).allowance(address(this), _target);\n if (allowance < _neededAmount) {\n if (allowance > 0) {\n ERC20(_asset).safeApprove(_target, 0);\n }\n ERC20(_asset).safeApprove(_target, type(uint256).max);\n }\n }\n\n /// @dev Helper to transfer full asset balance from the current contract to a target\n function __pushFullAssetBalance(address _target, address _asset)\n internal\n returns (uint256 amountTransferred_)\n {\n amountTransferred_ = ERC20(_asset).balanceOf(address(this));\n if (amountTransferred_ > 0) {\n ERC20(_asset).safeTransfer(_target, amountTransferred_);\n }\n\n return amountTransferred_;\n }\n\n /// @dev Helper to transfer full asset balances from the current contract to a target\n function __pushFullAssetBalances(address _target, address[] memory _assets)\n internal\n returns (uint256[] memory amountsTransferred_)\n {\n amountsTransferred_ = new uint256[](_assets.length);\n for (uint256 i; i < _assets.length; i++) {\n ERC20 assetContract = ERC20(_assets[i]);\n amountsTransferred_[i] = assetContract.balanceOf(address(this));\n if (amountsTransferred_[i] > 0) {\n assetContract.safeTransfer(_target, amountsTransferred_[i]);\n }\n }\n\n return amountsTransferred_;\n }\n}\n" }, "contracts/release/utils/beacon-proxy/BeaconProxy.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n\n (c) Enzyme Council \n\n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\n\nimport \"./IBeacon.sol\";\n\n/// @title BeaconProxy Contract\n/// @author Enzyme Council \n/// @notice A proxy contract that uses the beacon pattern for instant upgrades\ncontract BeaconProxy {\n address private immutable BEACON;\n\n constructor(bytes memory _constructData, address _beacon) public {\n BEACON = _beacon;\n\n (bool success, bytes memory returnData) = IBeacon(_beacon).getCanonicalLib().delegatecall(\n _constructData\n );\n require(success, string(returnData));\n }\n\n // solhint-disable-next-line no-complex-fallback\n fallback() external payable {\n address contractLogic = IBeacon(BEACON).getCanonicalLib();\n assembly {\n calldatacopy(0x0, 0x0, calldatasize())\n let success := delegatecall(\n sub(gas(), 10000),\n contractLogic,\n 0x0,\n calldatasize(),\n 0,\n 0\n )\n let retSz := returndatasize()\n returndatacopy(0, 0, retSz)\n switch success\n case 0 {\n revert(0, retSz)\n }\n default {\n return(0, retSz)\n }\n }\n }\n\n receive() external payable {}\n}\n" }, "contracts/release/utils/beacon-proxy/BeaconProxyFactory.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n\n (c) Enzyme Council \n\n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\n\nimport \"./BeaconProxy.sol\";\nimport \"./IBeaconProxyFactory.sol\";\n\n/// @title BeaconProxyFactory Contract\n/// @author Enzyme Council \n/// @notice Factory contract that deploys beacon proxies\nabstract contract BeaconProxyFactory is IBeaconProxyFactory {\n event CanonicalLibSet(address nextCanonicalLib);\n\n event ProxyDeployed(address indexed caller, address proxy, bytes constructData);\n\n address private canonicalLib;\n\n constructor(address _canonicalLib) public {\n __setCanonicalLib(_canonicalLib);\n }\n\n /// @notice Deploys a new proxy instance\n /// @param _constructData The constructor data with which to call `init()` on the deployed proxy\n /// @return proxy_ The proxy address\n function deployProxy(bytes memory _constructData) public override returns (address proxy_) {\n proxy_ = address(new BeaconProxy(_constructData, address(this)));\n\n emit ProxyDeployed(msg.sender, proxy_, _constructData);\n\n return proxy_;\n }\n\n /// @notice Gets the canonical lib used by all proxies\n /// @return canonicalLib_ The canonical lib\n function getCanonicalLib() public view override returns (address canonicalLib_) {\n return canonicalLib;\n }\n\n /// @notice Gets the contract owner\n /// @return owner_ The contract owner\n function getOwner() public view virtual returns (address owner_);\n\n /// @notice Sets the next canonical lib used by all proxies\n /// @param _nextCanonicalLib The next canonical lib\n function setCanonicalLib(address _nextCanonicalLib) public override {\n require(\n msg.sender == getOwner(),\n \"setCanonicalLib: Only the owner can call this function\"\n );\n\n __setCanonicalLib(_nextCanonicalLib);\n }\n\n /// @dev Helper to set the next canonical lib\n function __setCanonicalLib(address _nextCanonicalLib) internal {\n canonicalLib = _nextCanonicalLib;\n\n emit CanonicalLibSet(_nextCanonicalLib);\n }\n}\n" }, "contracts/release/utils/beacon-proxy/IBeacon.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n\n (c) Enzyme Council \n\n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\npragma solidity 0.6.12;\n\n/// @title IBeacon interface\n/// @author Enzyme Council \ninterface IBeacon {\n function getCanonicalLib() external view returns (address);\n}\n" }, "contracts/release/utils/beacon-proxy/IBeaconProxyFactory.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\n\n/*\n This file is part of the Enzyme Protocol.\n\n (c) Enzyme Council \n\n For the full license information, please view the LICENSE\n file that was distributed with this source code.\n*/\n\nimport \"./IBeacon.sol\";\n\npragma solidity 0.6.12;\n\n/// @title IBeaconProxyFactory interface\n/// @author Enzyme Council \ninterface IBeaconProxyFactory is IBeacon {\n function deployProxy(bytes memory _constructData) external returns (address proxy_);\n\n function setCanonicalLib(address _canonicalLib) external;\n}\n" } } }