// SPDX-License-Identifier: MITpragmasolidity >=0.6.2 <0.8.0;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in// construction, since the code is only stored at the end of the// constructor execution.uint256 size;
// solhint-disable-next-line no-inline-assemblyassembly { size :=extcodesize(account) }
return size >0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable recipient, uint256 amount) internal{
require(address(this).balance>= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCall(address target, bytesmemory data, stringmemory errorMessage) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target, bytesmemory data, uint256 value) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target, bytesmemory data, uint256 value, stringmemory errorMessage) internalreturns (bytesmemory) {
require(address(this).balance>= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytesmemory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target, bytesmemory data, stringmemory errorMessage) internalviewreturns (bytesmemory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytesmemory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target, bytesmemory data, stringmemory errorMessage) internalreturns (bytesmemory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytesmemory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function_verifyCallResult(bool success, bytesmemory returndata, stringmemory errorMessage) privatepurereturns(bytesmemory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assembly// solhint-disable-next-line no-inline-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
Contract Source Code
File 2 of 11: BaseRewardPool.sol
// SPDX-License-Identifier: MITpragmasolidity 0.6.12;/**
*Submitted for verification at Etherscan.io on 2020-07-17
*//*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: BaseRewardPool.sol
*
* Docs: https://docs.synthetix.io/
*
*
* MIT License
* ===========
*
* Copyright (c) 2020 Synthetix
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/import"./Interfaces.sol";
import"./interfaces/MathUtil.sol";
import"@openzeppelin/contracts-0.6/math/SafeMath.sol";
import"@openzeppelin/contracts-0.6/token/ERC20/IERC20.sol";
import"@openzeppelin/contracts-0.6/utils/Address.sol";
import"@openzeppelin/contracts-0.6/token/ERC20/SafeERC20.sol";
/**
* @title BaseRewardPool
* @author Synthetix -> ConvexFinance
* @notice Unipool rewards contract that is re-deployed from rFactory for each staking pool.
* @dev Changes made here by ConvexFinance are to do with the delayed reward allocation. Curve is queued for
* rewards and the distribution only begins once the new rewards are sufficiently large, or the epoch
* has ended. Additionally, enables hooks for `extraRewards` that can be enabled at any point to
* distribute a child reward token (i.e. a secondary one from Curve, or a seperate one).
*/contractBaseRewardPool{
usingSafeMathforuint256;
usingSafeERC20forIERC20;
IERC20 publicimmutable rewardToken;
IERC20 publicimmutable stakingToken;
uint256publicconstant duration =7days;
addresspublicimmutable operator;
addresspublicimmutable rewardManager;
uint256publicimmutable pid;
uint256public periodFinish =0;
uint256public rewardRate =0;
uint256public lastUpdateTime;
uint256public rewardPerTokenStored;
uint256public queuedRewards =0;
uint256public currentRewards =0;
uint256public historicalRewards =0;
uint256publicconstant newRewardRatio =830;
uint256private _totalSupply;
mapping(address=>uint256) public userRewardPerTokenPaid;
mapping(address=>uint256) public rewards;
mapping(address=>uint256) private _balances;
address[] public extraRewards;
eventRewardAdded(uint256 reward);
eventStaked(addressindexed user, uint256 amount);
eventWithdrawn(addressindexed user, uint256 amount);
eventRewardPaid(addressindexed user, uint256 reward);
eventTransfer(addressindexedfrom, addressindexed to, uint256 value);
/**
* @dev This is called directly from RewardFactory
* @param pid_ Effectively the pool identifier - used in the Booster
* @param stakingToken_ Pool LP token
* @param rewardToken_ Crv
* @param operator_ Booster
* @param rewardManager_ RewardFactory
*/constructor(uint256 pid_,
address stakingToken_,
address rewardToken_,
address operator_,
address rewardManager_
) public{
pid = pid_;
stakingToken = IERC20(stakingToken_);
rewardToken = IERC20(rewardToken_);
operator = operator_;
rewardManager = rewardManager_;
}
functiontotalSupply() publicviewvirtualreturns (uint256) {
return _totalSupply;
}
functionbalanceOf(address account) publicviewvirtualreturns (uint256) {
return _balances[account];
}
functionextraRewardsLength() externalviewreturns (uint256) {
return extraRewards.length;
}
functionaddExtraReward(address _reward) externalreturns(bool){
require(msg.sender== rewardManager, "!authorized");
require(_reward !=address(0),"!reward setting");
if(extraRewards.length>=12){
returnfalse;
}
extraRewards.push(_reward);
returntrue;
}
functionclearExtraRewards() external{
require(msg.sender== rewardManager, "!authorized");
delete extraRewards;
}
modifierupdateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account !=address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
functionlastTimeRewardApplicable() publicviewreturns (uint256) {
return MathUtil.min(block.timestamp, periodFinish);
}
functionrewardPerToken() publicviewreturns (uint256) {
if (totalSupply() ==0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
functionearned(address account) publicviewreturns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
functionstake(uint256 _amount)
publicreturns(bool)
{
_processStake(_amount, msg.sender);
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
emit Staked(msg.sender, _amount);
returntrue;
}
functionstakeAll() externalreturns(bool){
uint256 balance = stakingToken.balanceOf(msg.sender);
stake(balance);
returntrue;
}
functionstakeFor(address _for, uint256 _amount)
publicreturns(bool)
{
_processStake(_amount, _for);
//take away from sender
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
emit Staked(_for, _amount);
returntrue;
}
/**
* @dev Generic internal staking function that basically does 3 things: update rewards based
* on previous balance, trigger also on any child contracts, then update balances.
* @param _amount Units to add to the users balance
* @param _receiver Address of user who will receive the stake
*/function_processStake(uint256 _amount, address _receiver) internalupdateReward(_receiver) {
require(_amount >0, 'RewardPool : Cannot stake 0');
//also stake to linked rewardsfor(uint i=0; i < extraRewards.length; i++){
IRewards(extraRewards[i]).stake(_receiver, _amount);
}
_totalSupply = _totalSupply.add(_amount);
_balances[_receiver] = _balances[_receiver].add(_amount);
emit Transfer(address(0), _receiver, _amount);
}
functionwithdraw(uint256 amount, bool claim)
publicupdateReward(msg.sender)
returns(bool)
{
require(amount >0, 'RewardPool : Cannot withdraw 0');
//also withdraw from linked rewardsfor(uint i=0; i < extraRewards.length; i++){
IRewards(extraRewards[i]).withdraw(msg.sender, amount);
}
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
stakingToken.safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount);
if(claim){
getReward(msg.sender,true);
}
emit Transfer(msg.sender, address(0), amount);
returntrue;
}
functionwithdrawAll(bool claim) external{
withdraw(_balances[msg.sender],claim);
}
functionwithdrawAndUnwrap(uint256 amount, bool claim) publicreturns(bool){
_withdrawAndUnwrapTo(amount, msg.sender, msg.sender);
//get rewards tooif(claim){
getReward(msg.sender,true);
}
returntrue;
}
function_withdrawAndUnwrapTo(uint256 amount, addressfrom, address receiver) internalupdateReward(from) returns(bool){
//also withdraw from linked rewardsfor(uint i=0; i < extraRewards.length; i++){
IRewards(extraRewards[i]).withdraw(from, amount);
}
_totalSupply = _totalSupply.sub(amount);
_balances[from] = _balances[from].sub(amount);
//tell operator to withdraw from here directly to user
IDeposit(operator).withdrawTo(pid,amount,receiver);
emit Withdrawn(from, amount);
emit Transfer(from, address(0), amount);
returntrue;
}
functionwithdrawAllAndUnwrap(bool claim) external{
withdrawAndUnwrap(_balances[msg.sender],claim);
}
/**
* @dev Gives a staker their rewards, with the option of claiming extra rewards
* @param _account Account for which to claim
* @param _claimExtras Get the child rewards too?
*/functiongetReward(address _account, bool _claimExtras) publicupdateReward(_account) returns(bool){
uint256 reward = earned(_account);
if (reward >0) {
rewards[_account] =0;
rewardToken.safeTransfer(_account, reward);
IDeposit(operator).rewardClaimed(pid, _account, reward);
emit RewardPaid(_account, reward);
}
//also get rewards from linked rewardsif(_claimExtras){
for(uint i=0; i < extraRewards.length; i++){
IRewards(extraRewards[i]).getReward(_account);
}
}
returntrue;
}
/**
* @dev Called by a staker to get their allocated rewards
*/functiongetReward() externalreturns(bool){
getReward(msg.sender,true);
returntrue;
}
/**
* @dev Processes queued rewards in isolation, providing the period has finished.
* This allows a cheaper way to trigger rewards on low value pools.
*/functionprocessIdleRewards() external{
if (block.timestamp>= periodFinish && queuedRewards >0) {
notifyRewardAmount(queuedRewards);
queuedRewards =0;
}
}
/**
* @dev Called by the booster to allocate new Crv rewards to this pool
* Curve is queued for rewards and the distribution only begins once the new rewards are sufficiently
* large, or the epoch has ended.
*/functionqueueNewRewards(uint256 _rewards) externalreturns(bool){
require(msg.sender== operator, "!authorized");
_rewards = _rewards.add(queuedRewards);
if (block.timestamp>= periodFinish) {
notifyRewardAmount(_rewards);
queuedRewards =0;
returntrue;
}
//et = now - (finish-duration)uint256 elapsedTime =block.timestamp.sub(periodFinish.sub(duration));
//current at now: rewardRate * elapsedTimeuint256 currentAtNow = rewardRate * elapsedTime;
uint256 queuedRatio = currentAtNow.mul(1000).div(_rewards);
//uint256 queuedRatio = currentRewards.mul(1000).div(_rewards);if(queuedRatio < newRewardRatio){
notifyRewardAmount(_rewards);
queuedRewards =0;
}else{
queuedRewards = _rewards;
}
returntrue;
}
functionnotifyRewardAmount(uint256 reward)
internalupdateReward(address(0))
{
historicalRewards = historicalRewards.add(reward);
if (block.timestamp>= periodFinish) {
rewardRate = reward.div(duration);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
reward = reward.add(leftover);
rewardRate = reward.div(duration);
}
currentRewards = reward;
lastUpdateTime =block.timestamp;
periodFinish =block.timestamp.add(duration);
emit RewardAdded(reward);
}
}
Contract Source Code
File 3 of 11: BaseRewardPool4626.sol
// SPDX-License-Identifier: MITpragmasolidity 0.6.12;import { BaseRewardPool, IDeposit } from"./BaseRewardPool.sol";
import { IERC4626, IERC20Metadata } from"./interfaces/IERC4626.sol";
import { IERC20 } from"@openzeppelin/contracts-0.6/token/ERC20/IERC20.sol";
import { ReentrancyGuard } from"@openzeppelin/contracts-0.6/utils/ReentrancyGuard.sol";
import { SafeERC20 } from"@openzeppelin/contracts-0.6/token/ERC20/SafeERC20.sol";
/**
* @title BaseRewardPool4626
* @notice Simply wraps the BaseRewardPool with the new IERC4626 Vault standard functions.
* @dev See https://github.com/fei-protocol/ERC4626/blob/main/src/interfaces/IERC4626.sol#L58
* This is not so much a vault as a Reward Pool, therefore asset:share ratio is always 1:1.
* To create most utility for this RewardPool, the "asset" has been made to be the crvLP token,
* as opposed to the cvxLP token. Therefore, users can easily deposit crvLP, and it will first
* go to the Booster and mint the cvxLP before performing the normal staking function.
*/contractBaseRewardPool4626isBaseRewardPool, ReentrancyGuard, IERC4626{
usingSafeERC20forIERC20;
/**
* @notice The address of the underlying ERC20 token used for
* the Vault for accounting, depositing, and withdrawing.
*/addresspublicoverride asset;
mapping (address=>mapping (address=>uint256)) private _allowances;
/**
* @dev See BaseRewardPool.sol
*/constructor(uint256 pid_,
address stakingToken_,
address rewardToken_,
address operator_,
address rewardManager_,
address lptoken_
) publicBaseRewardPool(pid_, stakingToken_, rewardToken_, operator_, rewardManager_) {
asset = lptoken_;
IERC20(asset).safeApprove(operator_, type(uint256).max);
}
/**
* @notice Total amount of the underlying asset that is "managed" by Vault.
*/functiontotalAssets() externalviewvirtualoverridereturns(uint256){
return totalSupply();
}
/**
* @notice Mints `shares` Vault shares to `receiver`.
* @dev Because `asset` is not actually what is collected here, first wrap to required token in the booster.
*/functiondeposit(uint256 assets, address receiver) publicvirtualoverridenonReentrantreturns (uint256) {
// Transfer "asset" (crvLP) from sender
IERC20(asset).safeTransferFrom(msg.sender, address(this), assets);
// Convert crvLP to cvxLP through normal booster deposit process, but don't stakeuint256 balBefore = stakingToken.balanceOf(address(this));
IDeposit(operator).deposit(pid, assets, false);
uint256 balAfter = stakingToken.balanceOf(address(this));
require(balAfter.sub(balBefore) >= assets, "!deposit");
// Perform stake manually, now that the funds have been received
_processStake(assets, receiver);
emit Deposit(msg.sender, receiver, assets, assets);
emit Staked(receiver, assets);
return assets;
}
/**
* @notice Mints exactly `shares` Vault shares to `receiver`
* by depositing `assets` of underlying tokens.
*/functionmint(uint256 shares, address receiver) externalvirtualoverridereturns (uint256) {
return deposit(shares, receiver);
}
/**
* @notice Redeems `shares` from `owner` and sends `assets`
* of underlying tokens to `receiver`.
*/functionwithdraw(uint256 assets,
address receiver,
address owner
) publicvirtualoverridenonReentrantreturns (uint256) {
if (msg.sender!= owner) {
_approve(owner, msg.sender, _allowances[owner][msg.sender].sub(assets, "ERC4626: withdrawal amount exceeds allowance"));
}
_withdrawAndUnwrapTo(assets, owner, receiver);
emit Withdraw(msg.sender, receiver, owner, assets, assets);
return assets;
}
/**
* @notice Redeems `shares` from `owner` and sends `assets`
* of underlying tokens to `receiver`.
*/functionredeem(uint256 shares,
address receiver,
address owner
) externalvirtualoverridereturns (uint256) {
return withdraw(shares, receiver, owner);
}
/**
* @notice The amount of shares that the vault would
* exchange for the amount of assets provided, in an
* ideal scenario where all the conditions are met.
*/functionconvertToShares(uint256 assets) publicviewvirtualoverridereturns (uint256) {
return assets;
}
/**
* @notice The amount of assets that the vault would
* exchange for the amount of shares provided, in an
* ideal scenario where all the conditions are met.
*/functionconvertToAssets(uint256 shares) publicviewvirtualoverridereturns (uint256) {
return shares;
}
/**
* @notice Total number of underlying assets that can
* be deposited by `owner` into the Vault, where `owner`
* corresponds to the input parameter `receiver` of a
* `deposit` call.
*/functionmaxDeposit(address/* owner */) publicviewvirtualoverridereturns (uint256) {
returntype(uint256).max;
}
/**
* @notice Allows an on-chain or off-chain user to simulate
* the effects of their deposit at the current block, given
* current on-chain conditions.
*/functionpreviewDeposit(uint256 assets) externalviewvirtualoverridereturns(uint256){
return convertToShares(assets);
}
/**
* @notice Total number of underlying shares that can be minted
* for `owner`, where `owner` corresponds to the input
* parameter `receiver` of a `mint` call.
*/functionmaxMint(address owner) externalviewvirtualoverridereturns (uint256) {
return maxDeposit(owner);
}
/**
* @notice Allows an on-chain or off-chain user to simulate
* the effects of their mint at the current block, given
* current on-chain conditions.
*/functionpreviewMint(uint256 shares) externalviewvirtualoverridereturns(uint256){
return convertToAssets(shares);
}
/**
* @notice Total number of underlying assets that can be
* withdrawn from the Vault by `owner`, where `owner`
* corresponds to the input parameter of a `withdraw` call.
*/functionmaxWithdraw(address owner) publicviewvirtualoverridereturns (uint256) {
return balanceOf(owner);
}
/**
* @notice Allows an on-chain or off-chain user to simulate
* the effects of their withdrawal at the current block,
* given current on-chain conditions.
*/functionpreviewWithdraw(uint256 assets) publicviewvirtualoverridereturns(uint256 shares){
return convertToShares(assets);
}
/**
* @notice Total number of underlying shares that can be
* redeemed from the Vault by `owner`, where `owner` corresponds
* to the input parameter of a `redeem` call.
*/functionmaxRedeem(address owner) externalviewvirtualoverridereturns (uint256) {
return maxWithdraw(owner);
}
/**
* @notice Allows an on-chain or off-chain user to simulate
* the effects of their redeemption at the current block,
* given current on-chain conditions.
*/functionpreviewRedeem(uint256 shares) externalviewvirtualoverridereturns(uint256){
return previewWithdraw(shares);
}
/* ========== IERC20 ========== *//**
* @dev Returns the name of the token.
*/functionname() externalviewoverridereturns (stringmemory) {
returnstring(
abi.encodePacked(IERC20Metadata(address(stakingToken)).name(), " Vault")
);
}
/**
* @dev Returns the symbol of the token.
*/functionsymbol() externalviewoverridereturns (stringmemory) {
returnstring(
abi.encodePacked(IERC20Metadata(address(stakingToken)).symbol(), "-vault")
);
}
/**
* @dev Returns the decimals places of the token.
*/functiondecimals() externalviewoverridereturns (uint8) {
return18;
}
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() publicviewoverride(BaseRewardPool, IERC20) returns (uint256) {
return BaseRewardPool.totalSupply();
}
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) publicviewoverride(BaseRewardPool, IERC20) returns (uint256) {
return BaseRewardPool.balanceOf(account);
}
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address/* recipient */, uint256/* amount */) externaloverridereturns (bool) {
revert("ERC4626: Not supported");
}
/**
* @dev See {IERC20-allowance}.
*/functionallowance(address owner, address spender) publicviewvirtualoverridereturns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/functionapprove(address spender, uint256 amount) publicvirtualoverridereturns (bool) {
_approve(msg.sender, spender, amount);
returntrue;
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*/function_approve(address owner, address spender, uint256 amount) internalvirtual{
require(owner !=address(0), "ERC4626: approve from the zero address");
require(spender !=address(0), "ERC4626: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*/functiontransferFrom(address/* sender */, address/* recipient */, uint256/* amount */) externaloverridereturns (bool) {
revert("ERC4626: Not supported");
}
}
Contract Source Code
File 4 of 11: IERC20.sol
// SPDX-License-Identifier: MITpragmasolidity >=0.6.0 <0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address recipient, uint256 amount) externalreturns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/functionallowance(address owner, address spender) externalviewreturns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/functionapprove(address spender, uint256 amount) externalreturns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransferFrom(address sender, address recipient, uint256 amount) externalreturns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
}
Contract Source Code
File 5 of 11: IERC20Metadata.sol
// SPDX-License-Identifier: MITpragmasolidity 0.6.12;import { IERC20 } from"@openzeppelin/contracts-0.6/token/ERC20/IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/interfaceIERC20MetadataisIERC20{
/**
* @dev Returns the name of the token.
*/functionname() externalviewreturns (stringmemory);
/**
* @dev Returns the symbol of the token.
*/functionsymbol() externalviewreturns (stringmemory);
/**
* @dev Returns the decimals places of the token.
*/functiondecimals() externalviewreturns (uint8);
}
Contract Source Code
File 6 of 11: IERC4626.sol
// SPDX-License-Identifier: MITpragmasolidity 0.6.12;import { IERC20Metadata } from"./IERC20Metadata.sol";
/// @title ERC4626 interface/// See: https://eips.ethereum.org/EIPS/eip-4626abstractcontractIERC4626isIERC20Metadata{
/*////////////////////////////////////////////////////////
Events
////////////////////////////////////////////////////////*//// @notice `caller` has exchanged `assets` for `shares`, and transferred those `shares` to `owner`eventDeposit(addressindexed caller,
addressindexed owner,
uint256 assets,
uint256 shares
);
/// @notice `caller` has exchanged `shares`, owned by `owner`, for/// `assets`, and transferred those `assets` to `receiver`.eventWithdraw(addressindexed caller,
addressindexed receiver,
addressindexed owner,
uint256 assets,
uint256 shares
);
/*////////////////////////////////////////////////////////
Vault properties
////////////////////////////////////////////////////////*//// @notice The address of the underlying ERC20 token used for/// the Vault for accounting, depositing, and withdrawing.functionasset() externalviewvirtualreturns(address);
/// @notice Total amount of the underlying asset that/// is "managed" by Vault.functiontotalAssets() externalviewvirtualreturns(uint256);
/*////////////////////////////////////////////////////////
Deposit/Withdrawal Logic
////////////////////////////////////////////////////////*//// @notice Mints `shares` Vault shares to `receiver` by/// depositing exactly `assets` of underlying tokens.functiondeposit(uint256 assets, address receiver) externalvirtualreturns(uint256 shares);
/// @notice Mints exactly `shares` Vault shares to `receiver`/// by depositing `assets` of underlying tokens.functionmint(uint256 shares, address receiver) externalvirtualreturns(uint256 assets);
/// @notice Redeems `shares` from `owner` and sends `assets`/// of underlying tokens to `receiver`.functionwithdraw(uint256 assets, address receiver, address owner) externalvirtualreturns(uint256 shares);
/// @notice Redeems `shares` from `owner` and sends `assets`/// of underlying tokens to `receiver`.functionredeem(uint256 shares, address receiver, address owner) externalvirtualreturns(uint256 assets);
/*////////////////////////////////////////////////////////
Vault Accounting Logic
////////////////////////////////////////////////////////*//// @notice The amount of shares that the vault would/// exchange for the amount of assets provided, in an/// ideal scenario where all the conditions are met.functionconvertToShares(uint256 assets) externalviewvirtualreturns(uint256 shares);
/// @notice The amount of assets that the vault would/// exchange for the amount of shares provided, in an/// ideal scenario where all the conditions are met.functionconvertToAssets(uint256 shares) externalviewvirtualreturns(uint256 assets);
/// @notice Total number of underlying assets that can/// be deposited by `owner` into the Vault, where `owner`/// corresponds to the input parameter `receiver` of a/// `deposit` call.functionmaxDeposit(address owner) externalviewvirtualreturns(uint256 maxAssets);
/// @notice Allows an on-chain or off-chain user to simulate/// the effects of their deposit at the current block, given/// current on-chain conditions.functionpreviewDeposit(uint256 assets) externalviewvirtualreturns(uint256 shares);
/// @notice Total number of underlying shares that can be minted/// for `owner`, where `owner` corresponds to the input/// parameter `receiver` of a `mint` call.functionmaxMint(address owner) externalviewvirtualreturns(uint256 maxShares);
/// @notice Allows an on-chain or off-chain user to simulate/// the effects of their mint at the current block, given/// current on-chain conditions.functionpreviewMint(uint256 shares) externalviewvirtualreturns(uint256 assets);
/// @notice Total number of underlying assets that can be/// withdrawn from the Vault by `owner`, where `owner`/// corresponds to the input parameter of a `withdraw` call.functionmaxWithdraw(address owner) externalviewvirtualreturns(uint256 maxAssets);
/// @notice Allows an on-chain or off-chain user to simulate/// the effects of their withdrawal at the current block,/// given current on-chain conditions.functionpreviewWithdraw(uint256 assets) externalviewvirtualreturns(uint256 shares);
/// @notice Total number of underlying shares that can be/// redeemed from the Vault by `owner`, where `owner` corresponds/// to the input parameter of a `redeem` call.functionmaxRedeem(address owner) externalviewvirtualreturns(uint256 maxShares);
/// @notice Allows an on-chain or off-chain user to simulate/// the effects of their redeemption at the current block,/// given current on-chain conditions.functionpreviewRedeem(uint256 shares) externalviewvirtualreturns(uint256 assets);
}
// SPDX-License-Identifier: MITpragmasolidity 0.6.12;/**
* @dev Standard math utilities missing in the Solidity language.
*/libraryMathUtil{
/**
* @dev Returns the smallest of two numbers.
*/functionmin(uint256 a, uint256 b) internalpurereturns (uint256) {
return a < b ? a : b;
}
}
Contract Source Code
File 9 of 11: ReentrancyGuard.sol
// SPDX-License-Identifier: MITpragmasolidity >=0.6.0 <0.8.0;/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/abstractcontractReentrancyGuard{
// Booleans are more expensive than uint256 or any type that takes up a full// word because each write operation emits an extra SLOAD to first read the// slot's contents, replace the bits taken up by the boolean, and then write// back. This is the compiler's defense against contract upgrades and// pointer aliasing, and it cannot be disabled.// The values being non-zero value makes deployment a bit more expensive,// but in exchange the refund on every call to nonReentrant will be lower in// amount. Since refunds are capped to a percentage of the total// transaction's gas, it is best to keep them low in cases like this one, to// increase the likelihood of the full refund coming into effect.uint256privateconstant _NOT_ENTERED =1;
uint256privateconstant _ENTERED =2;
uint256private _status;
constructor () internal{
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/modifiernonReentrant() {
// On the first call to nonReentrant, _notEntered will be truerequire(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
Contract Source Code
File 10 of 11: SafeERC20.sol
// SPDX-License-Identifier: MITpragmasolidity >=0.6.0 <0.8.0;import"./IERC20.sol";
import"../../math/SafeMath.sol";
import"../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/librarySafeERC20{
usingSafeMathforuint256;
usingAddressforaddress;
functionsafeTransfer(IERC20 token, address to, uint256 value) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
functionsafeTransferFrom(IERC20 token, addressfrom, address to, uint256 value) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/functionsafeApprove(IERC20 token, address spender, uint256 value) internal{
// safeApprove should only be called when setting an initial allowance,// or when resetting it to zero. To increase and decrease it, use// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'// solhint-disable-next-line max-line-lengthrequire((value ==0) || (token.allowance(address(this), spender) ==0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
functionsafeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal{
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
functionsafeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal{
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/function_callOptionalReturn(IERC20 token, bytesmemory data) private{
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that// the target address contains contract code and also asserts for success in the low-level call.bytesmemory returndata =address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length>0) { // Return data is optional// solhint-disable-next-line max-line-lengthrequire(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
Contract Source Code
File 11 of 11: SafeMath.sol
// SPDX-License-Identifier: MITpragmasolidity >=0.6.0 <0.8.0;/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/librarySafeMath{
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/functiontryAdd(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/functiontrySub(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/functiontryMul(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the// benefit is lost if 'b' is also tested.// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522if (a ==0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/functiontryDiv(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
if (b ==0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/functiontryMod(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
if (b ==0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/functionadd(uint256 a, uint256 b) internalpurereturns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/functionsub(uint256 a, uint256 b) internalpurereturns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/functionmul(uint256 a, uint256 b) internalpurereturns (uint256) {
if (a ==0) return0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/functiondiv(uint256 a, uint256 b) internalpurereturns (uint256) {
require(b >0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/functionmod(uint256 a, uint256 b) internalpurereturns (uint256) {
require(b >0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/functionsub(uint256 a, uint256 b, stringmemory errorMessage) internalpurereturns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/functiondiv(uint256 a, uint256 b, stringmemory errorMessage) internalpurereturns (uint256) {
require(b >0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/functionmod(uint256 a, uint256 b, stringmemory errorMessage) internalpurereturns (uint256) {
require(b >0, errorMessage);
return a % b;
}
}