// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)pragmasolidity ^0.8.1;/**
* @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
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0// for contracts in construction, since the code is only stored at the end// of the constructor execution.return account.code.length>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://consensys.net/diligence/blog/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.8.0/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");
(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 functionCallWithValue(target, data, 0, "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");
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, 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) {
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, 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) {
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/functionverifyCallResultFromTarget(address target,
bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
if (success) {
if (returndata.length==0) {
// only check isContract if the call was successful and the return data is empty// otherwise we already know that it was a contractrequire(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function_revert(bytesmemory returndata, stringmemory errorMessage) privatepure{
// 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/// @solidity memory-safe-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
Contract Source Code
File 2 of 13: BoringERC20.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.7;// solhint-disable avoid-low-level-callsimport"./IBoringERC20.sol";
libraryBoringERC20{
bytes4privateconstant SIG_SYMBOL =0x95d89b41; // symbol()bytes4privateconstant SIG_NAME =0x06fdde03; // name()bytes4privateconstant SIG_DECIMALS =0x313ce567; // decimals()bytes4privateconstant SIG_TRANSFER =0xa9059cbb; // transfer(address,uint256)bytes4privateconstant SIG_TRANSFER_FROM =0x23b872dd; // transferFrom(address,address,uint256)functionreturnDataToString(bytesmemory data)
internalpurereturns (stringmemory)
{
if (data.length>=64) {
returnabi.decode(data, (string));
} elseif (data.length==32) {
uint8 i =0;
while (i <32&& data[i] !=0) {
i++;
}
bytesmemory bytesArray =newbytes(i);
for (i =0; i <32&& data[i] !=0; i++) {
bytesArray[i] = data[i];
}
returnstring(bytesArray);
} else {
return"???";
}
}
/// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string./// @param token The address of the ERC-20 token contract./// @return (string) Token symbol.functionsafeSymbol(IBoringERC20 token)
internalviewreturns (stringmemory)
{
(bool success, bytesmemory data) =address(token).staticcall(
abi.encodeWithSelector(SIG_SYMBOL)
);
return success ? returnDataToString(data) : "???";
}
/// @notice Provides a safe ERC20.name version which returns '???' as fallback string./// @param token The address of the ERC-20 token contract./// @return (string) Token name.functionsafeName(IBoringERC20 token)
internalviewreturns (stringmemory)
{
(bool success, bytesmemory data) =address(token).staticcall(
abi.encodeWithSelector(SIG_NAME)
);
return success ? returnDataToString(data) : "???";
}
/// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value./// @param token The address of the ERC-20 token contract./// @return (uint8) Token decimals.functionsafeDecimals(IBoringERC20 token) internalviewreturns (uint8) {
(bool success, bytesmemory data) =address(token).staticcall(
abi.encodeWithSelector(SIG_DECIMALS)
);
return success && data.length==32 ? abi.decode(data, (uint8)) : 18;
}
/// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations./// Reverts on a failed transfer./// @param token The address of the ERC-20 token./// @param to Transfer tokens to./// @param amount The token amount.functionsafeTransfer(
IBoringERC20 token,
address to,
uint256 amount
) internal{
(bool success, bytesmemory data) =address(token).call(
abi.encodeWithSelector(SIG_TRANSFER, to, amount)
);
require(
success && (data.length==0||abi.decode(data, (bool))),
"BoringERC20: Transfer failed"
);
}
/// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations./// Reverts on a failed transfer./// @param token The address of the ERC-20 token./// @param from Transfer tokens from./// @param to Transfer tokens to./// @param amount The token amount.functionsafeTransferFrom(
IBoringERC20 token,
addressfrom,
address to,
uint256 amount
) internal{
(bool success, bytesmemory data) =address(token).call(
abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)
);
require(
success && (data.length==0||abi.decode(data, (bool))),
"BoringERC20: TransferFrom failed"
);
}
}
Contract Source Code
File 3 of 13: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)pragmasolidity ^0.8.0;/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
}
Contract Source Code
File 4 of 13: EsProxyMaster.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.7;import"@openzeppelin/contracts/access/Ownable.sol";
import"@openzeppelin/contracts/security/ReentrancyGuard.sol";
import"@openzeppelin/contracts/utils/Address.sol";
import"./interfaces/IComplexRewarder.sol";
import'./interfaces/IEsTokenUsage.sol';
import'./interfaces/esMaster/IEsToken.sol';
import'./interfaces/esMaster/IBasedDistributorV2.sol';
import"../farm/v2/libraries/BoringERC20.sol";
import"../farm/v2/IUniswapV2Pair.sol";
//Special version of MasterChef that works with esTokens allocate()/deallocate() and proxy farming through an existing MasterChefcontractEsProxyMasterisOwnable, ReentrancyGuard, IEsTokenUsage{
usingBoringERC20forIBoringERC20;
// Info of each user.structUserInfo {
uint256 amount; // How many LP tokens the user has provided.uint256 rewardDebt; // Reward debt. See explanation below.uint256 rewardLockedUp; // Reward locked up.uint256 nextHarvestUntil; // When can the user harvest again.
}
// Info of each pool.structPoolInfo {
IEsToken esToken; // Address of LP token contract.uint256 allocPoint; // How many allocation points assigned to this pool. Token to distribute per block.uint256 lastRewardTimestamp; // Last timestamp of distribution.uint256 accTokenPerShare; // Accumulated Token per share, times 1e18. See below.uint256 harvestInterval; // Harvest interval in secondsuint256 totalLp; // Total token in Pool
IComplexRewarder[] rewarders; // Array of rewarder contract for pools with incentives
}
IBoringERC20 public rewardToken;
IBasedDistributorV2 public emissionMaster;
uintpublic emissionPid;
uint lastHarvestTimestamp;
// Token tokens created per seconduint256public tokenPerSec;
// Max harvest interval: 14 daysuint256publicconstant MAXIMUM_HARVEST_INTERVAL =14days;
// Info of each pool
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.mapping(uint256=>mapping(address=> UserInfo)) public userInfo;
mapping(address=>uint256) public esTokens;
// Total allocation points. Must be the sum of all allocation points in all pools.uint256public totalAllocPoint =0;
// The timestamp when Token mining starts.uint256public startTimestamp;
// Total locked up rewardsuint256public totalLockedUpRewards;
// Total Token in Token Pools (can be multiple pools)uint256public totalTokenInPools =0;
// The precision factoruint256privateimmutable ACC_TOKEN_PRECISION =1e12;
modifiervalidatePoolByPid(uint256 _pid) {
require(_pid < poolInfo.length, "Pool does not exist");
_;
}
eventAdd(uint256indexed pid,
uint256 allocPoint,
IEsToken indexed esToken,
uint256 harvestInterval,
IComplexRewarder[] indexed rewarders
);
eventSet(uint256indexed pid,
uint256 allocPoint,
uint256 harvestInterval,
IComplexRewarder[] indexed rewarders
);
eventUpdatePool(uint256indexed pid,
uint256 lastRewardTimestamp,
uint256 lpSupply,
uint256 accTokenPerShare
);
eventDeposit(addressindexed user, uint256indexed pid, uint256 amount);
eventWithdraw(addressindexed user, uint256indexed pid, uint256 amount);
eventEmissionRateUpdated(addressindexed caller,
uint256 previousValue,
uint256 newValue
);
eventRewardLockedUp(addressindexed user,
uint256indexed pid,
uint256 amountLockedUp
);
eventAllocPointsUpdated(addressindexed caller,
uint256 previousAmount,
uint256 newAmount
);
constructor(
IBoringERC20 _rewardToken
) {
//StartBlock always many years later from contract deployment
startTimestamp =block.timestamp+ (60*60*24*365);
rewardToken = _rewardToken;
//pushes a dummy pool to fill pid 0
poolInfo.push(
PoolInfo({
esToken: IEsToken(address(0)),
allocPoint: 0,
lastRewardTimestamp: 0,
accTokenPerShare: 0,
harvestInterval: 0,
totalLp: 0,
rewarders: new IComplexRewarder[](0)
})
);
}
// Set farming start, can call only oncefunctionstartFarming(IBoringERC20 _dummyToken, IBasedDistributorV2 _emissionMaster, uint _emissionPid) publiconlyOwner{
require(
block.timestamp< startTimestamp,
"start farming: farm started already"
);
uint dummySupply = _dummyToken.totalSupply();
require(_dummyToken.balanceOf(address(this)) == dummySupply, "Invalid token initialization");
require(address(_emissionMaster) !=address(0), "Invalid emission master");
emissionMaster = _emissionMaster;
emissionPid = _emissionPid;
_dummyToken.approve(address(emissionMaster), dummySupply);
emissionMaster.deposit(emissionPid, dummySupply);
uint256 length = poolInfo.length;
for (uint256 pid =1; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
pool.lastRewardTimestamp =block.timestamp;
}
startTimestamp =block.timestamp;
lastHarvestTimestamp =block.timestamp;
_updateEmissionRate();
}
functionpoolLength() externalviewreturns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.// Can add multiple pool with same lp token without messing up rewards, because each pool's balance is tracked using its own totalLpfunctionadd(uint256 _allocPoint,
IEsToken _esToken,
uint256 _harvestInterval,
IComplexRewarder[] calldata _rewarders
) publiconlyOwner{
require(_rewarders.length<=10, "add: too many rewarders");
require(
_harvestInterval <= MAXIMUM_HARVEST_INTERVAL,
"add: invalid harvest interval"
);
require(
Address.isContract(address(_esToken)),
"add: LP token must be a valid contract"
);
require(esTokens[address(_esToken)] ==0, "Pool already exists");
for (
uint256 rewarderId =0;
rewarderId < _rewarders.length;
++rewarderId
) {
require(
Address.isContract(address(_rewarders[rewarderId])),
"add: rewarder must be contract"
);
}
_massUpdatePools();
uint256 lastRewardTimestamp =block.timestamp> startTimestamp
? block.timestamp
: startTimestamp;
totalAllocPoint += _allocPoint;
uint pid = poolInfo.length;
esTokens[address(_esToken)] = pid;
poolInfo.push(
PoolInfo({
esToken: _esToken,
allocPoint: _allocPoint,
lastRewardTimestamp: lastRewardTimestamp,
accTokenPerShare: 0,
harvestInterval: _harvestInterval,
totalLp: 0,
rewarders: _rewarders
})
);
emit Add(
poolInfo.length-1,
_allocPoint,
_esToken,
_harvestInterval,
_rewarders
);
}
// Update the given pool's Token allocation point and deposit fee. Can only be called by the owner.functionset(uint256 _pid,
uint256 _allocPoint,
uint256 _harvestInterval,
IComplexRewarder[] calldata _rewarders
) publiconlyOwnervalidatePoolByPid(_pid) {
require(_rewarders.length<=10, "set: too many rewarders");
require(_pid !=0, "Not authorized");
require(
_harvestInterval <= MAXIMUM_HARVEST_INTERVAL,
"set: invalid harvest interval"
);
for (
uint256 rewarderId =0;
rewarderId < _rewarders.length;
++rewarderId
) {
require(
Address.isContract(address(_rewarders[rewarderId])),
"set: rewarder must be contract"
);
}
_massUpdatePools();
totalAllocPoint =
totalAllocPoint -
poolInfo[_pid].allocPoint +
_allocPoint;
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].harvestInterval = _harvestInterval;
poolInfo[_pid].rewarders = _rewarders;
emit Set(
_pid,
_allocPoint,
_harvestInterval,
_rewarders
);
}
// View function to see pending rewards on frontend.functionpendingTokens(uint256 _pid, address _user)
externalviewvalidatePoolByPid(_pid)
returns (address[] memory addresses,
string[] memory symbols,
uint256[] memory decimals,
uint256[] memory amounts
)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accTokenPerShare = pool.accTokenPerShare;
uint256 lpSupply = pool.totalLp;
if (block.timestamp> pool.lastRewardTimestamp && lpSupply !=0) {
uint256 multiplier =block.timestamp- pool.lastRewardTimestamp;
uint256 tokenReward = (multiplier *
tokenPerSec *
pool.allocPoint) /
totalAllocPoint;
accTokenPerShare += (
((tokenReward * ACC_TOKEN_PRECISION) / lpSupply)
);
}
uint256 pendingToken = (((user.amount * accTokenPerShare) /
ACC_TOKEN_PRECISION) - user.rewardDebt) + user.rewardLockedUp;
addresses =newaddress[](pool.rewarders.length+1);
symbols =newstring[](pool.rewarders.length+1);
amounts =newuint256[](pool.rewarders.length+1);
decimals =newuint256[](pool.rewarders.length+1);
addresses[0] =address(rewardToken);
symbols[0] = IBoringERC20(rewardToken).safeSymbol();
decimals[0] = IBoringERC20(rewardToken).safeDecimals();
amounts[0] = pendingToken;
for (
uint256 rewarderId =0;
rewarderId < pool.rewarders.length;
++rewarderId
) {
addresses[rewarderId +1] =address(
pool.rewarders[rewarderId].rewardToken()
);
symbols[rewarderId +1] = IBoringERC20(
pool.rewarders[rewarderId].rewardToken()
).safeSymbol();
decimals[rewarderId +1] = IBoringERC20(
pool.rewarders[rewarderId].rewardToken()
).safeDecimals();
amounts[rewarderId +1] = pool.rewarders[rewarderId].pendingTokens(
_pid,
_user
);
}
}
/// @notice View function to see pool rewards per secfunctionpoolRewardsPerSec(uint256 _pid)
externalviewvalidatePoolByPid(_pid)
returns (address[] memory addresses,
string[] memory symbols,
uint256[] memory decimals,
uint256[] memory rewardsPerSec
)
{
PoolInfo storage pool = poolInfo[_pid];
addresses =newaddress[](pool.rewarders.length+1);
symbols =newstring[](pool.rewarders.length+1);
decimals =newuint256[](pool.rewarders.length+1);
rewardsPerSec =newuint256[](pool.rewarders.length+1);
addresses[0] =address(rewardToken);
symbols[0] = IBoringERC20(rewardToken).safeSymbol();
decimals[0] = IBoringERC20(rewardToken).safeDecimals();
rewardsPerSec[0] =
(pool.allocPoint * tokenPerSec) /
totalAllocPoint;
for (
uint256 rewarderId =0;
rewarderId < pool.rewarders.length;
++rewarderId
) {
addresses[rewarderId +1] =address(
pool.rewarders[rewarderId].rewardToken()
);
symbols[rewarderId +1] = IBoringERC20(
pool.rewarders[rewarderId].rewardToken()
).safeSymbol();
decimals[rewarderId +1] = IBoringERC20(
pool.rewarders[rewarderId].rewardToken()
).safeDecimals();
rewardsPerSec[rewarderId +1] = pool
.rewarders[rewarderId]
.poolRewardsPerSec(_pid);
}
}
// View function to see rewarders for a poolfunctionpoolRewarders(uint256 _pid)
externalviewvalidatePoolByPid(_pid)
returns (address[] memory rewarders)
{
PoolInfo storage pool = poolInfo[_pid];
rewarders =newaddress[](pool.rewarders.length);
for (
uint256 rewarderId =0;
rewarderId < pool.rewarders.length;
++rewarderId
) {
rewarders[rewarderId] =address(pool.rewarders[rewarderId]);
}
}
// View function to see if user can harvest Token.functioncanHarvest(uint256 _pid, address _user)
publicviewvalidatePoolByPid(_pid)
returns (bool)
{
UserInfo storage user = userInfo[_pid][_user];
returnblock.timestamp>= startTimestamp &&block.timestamp>= user.nextHarvestUntil;
}
// Update reward vairables for all pools. Be careful of gas spending!functionmassUpdatePools() externalnonReentrant{
_massUpdatePools();
}
// Internal method for massUpdatePoolsfunction_massUpdatePools() internal{
for (uint256 pid =1; pid < poolInfo.length; ++pid) {
_updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.functionupdatePool(uint256 _pid) externalnonReentrant{
require(_pid !=0, "Not authorized");
_updatePool(_pid);
}
// Internal method for _updatePoolfunction_updatePool(uint256 _pid) internalvalidatePoolByPid(_pid) {
PoolInfo storage pool = poolInfo[_pid];
//harvests from parent chef and updates token per sec if necessary
_harvestAndValidateEmissions();
//call returns here if we did a massUpdateif (block.timestamp<= pool.lastRewardTimestamp) {
return;
}
uint256 lpSupply = pool.totalLp;
if (lpSupply ==0|| pool.allocPoint ==0) {
pool.lastRewardTimestamp =block.timestamp;
return;
}
uint256 multiplier =block.timestamp- pool.lastRewardTimestamp;
uint256 tokenReward = ((multiplier * tokenPerSec) * pool.allocPoint) /
totalAllocPoint;
pool.accTokenPerShare +=
(tokenReward * ACC_TOKEN_PRECISION) /
pool.totalLp;
pool.lastRewardTimestamp =block.timestamp;
emit UpdatePool(
_pid,
pool.lastRewardTimestamp,
lpSupply,
pool.accTokenPerShare
);
}
// Deposit tokens for Token allocation.functionallocate(address user, uint256 amount, bytescalldata data) externaloverridenonReentrant{
//only accepts calls by registered esToken contractsuint _pid = esTokens[msg.sender];
require(_pid !=0, "Not authorized");
_deposit(user, _pid, amount);
}
//Dedicated harvest function to avoid using allocatefunctionharvest(uint256 _pid) externalnonReentrantvalidatePoolByPid(_pid) {
require(_pid !=0, "Not authorized");
_deposit(msg.sender, _pid, 0);
}
// Deposit tokens for Token allocation.function_deposit(address userAddress, uint256 _pid, uint256 _amount)
internal{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][userAddress];
_updatePool(_pid);
payOrLockupPendingToken(_pid, userAddress);
if (_amount >0) {
user.amount += _amount;
if (address(pool.esToken) ==address(rewardToken)) {
totalTokenInPools += _amount;
}
}
user.rewardDebt =
(user.amount * pool.accTokenPerShare) /
ACC_TOKEN_PRECISION;
for (
uint256 rewarderId =0;
rewarderId < pool.rewarders.length;
++rewarderId
) {
pool.rewarders[rewarderId].onReward(
_pid,
userAddress,
user.amount
);
}
if (_amount >0) {
pool.totalLp += _amount;
}
emit Deposit(userAddress, _pid, _amount);
}
//withdraw tokensfunctiondeallocate(address userAddress, uint256 _amount, bytescalldata data) externaloverridenonReentrant{
uint _pid = esTokens[msg.sender];
require(_pid !=0, "Not authorized");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][userAddress];
require(user.amount >= _amount, "withdraw: user amount not enough");
//cannot withdraw more than pool's balancerequire(pool.totalLp >= _amount, "withdraw: pool total not enough");
_updatePool(_pid);
payOrLockupPendingToken(_pid, userAddress);
if (_amount >0) {
user.amount -= _amount;
if (address(pool.esToken) ==address(rewardToken)) {
totalTokenInPools -= _amount;
}
}
user.rewardDebt =
(user.amount * pool.accTokenPerShare) /
ACC_TOKEN_PRECISION;
for (
uint256 rewarderId =0;
rewarderId < pool.rewarders.length;
++rewarderId
) {
try pool.rewarders[rewarderId].onReward(
_pid,
userAddress,
user.amount
) {} catch {}
}
if (_amount >0) {
pool.totalLp -= _amount;
}
emit Withdraw(userAddress, _pid, _amount);
}
// Pay or lockup pending Token.functionpayOrLockupPendingToken(uint256 _pid, address userAddress) internal{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][userAddress];
if (user.nextHarvestUntil ==0&&block.timestamp>= startTimestamp) {
user.nextHarvestUntil =block.timestamp+ pool.harvestInterval;
}
uint256 pending = ((user.amount * pool.accTokenPerShare) /
ACC_TOKEN_PRECISION) - user.rewardDebt;
if (canHarvest(_pid, userAddress)) {
if (pending >0|| user.rewardLockedUp >0) {
uint256 pendingRewards = pending + user.rewardLockedUp;
// reset lockup
totalLockedUpRewards -= user.rewardLockedUp;
user.rewardLockedUp =0;
user.nextHarvestUntil =block.timestamp+ pool.harvestInterval;
// send rewards
safeTokenTransfer(userAddress, pendingRewards);
}
} elseif (pending >0) {
totalLockedUpRewards += pending;
user.rewardLockedUp += pending;
emit RewardLockedUp(userAddress, _pid, pending);
}
}
// Safe Token transfer function, just in case if rounding error causes pool do not have enough Token.functionsafeTokenTransfer(address _to, uint256 _amount) internal{
if (rewardToken.balanceOf(address(this)) > totalTokenInPools) {
uint256 tokenBal = rewardToken.balanceOf(address(this)) -
totalTokenInPools;
if (_amount >= tokenBal) {
rewardToken.safeTransfer(_to, tokenBal);
} elseif (_amount >0) {
rewardToken.safeTransfer(_to, _amount);
}
}
}
function_harvestAndValidateEmissions() internal{
(,,,,,uint harvestInterval,) = emissionMaster.poolInfo(emissionPid);
if(block.timestamp<= lastHarvestTimestamp + harvestInterval) {
return;
}
uint preBalance = rewardToken.balanceOf(address(this));
emissionMaster.deposit(emissionPid, 0);
uint derivedTokenPerSec = (rewardToken.balanceOf(address(this)) - preBalance) / (block.timestamp- lastHarvestTimestamp);
// set last timestamp to avoid harvesting during massUpdate
lastHarvestTimestamp =block.timestamp;
if(derivedTokenPerSec != tokenPerSec) {
_updateEmissionRate();
}
}
functionupdateEmissionRate() publiconlyOwner{
_updateEmissionRate();
}
function_updateEmissionRate() internal{
//recalculates external emission rateuint newTokenPerSec;
{
(,uint parentAllocPoint,,,,,) = emissionMaster.poolInfo(emissionPid);
uint parentTotalAllocPoint = emissionMaster.totalAllocPoint();
uint parentTokenPerSec = emissionMaster.albPerSec();
uint teamPercent = emissionMaster.teamPercent();
uint investorPercent = emissionMaster.investorPercent();
uint treasuryPercent = emissionMaster.treasuryPercent();
uint lpPercent =1000- teamPercent - investorPercent - treasuryPercent;
newTokenPerSec = (parentTokenPerSec * parentAllocPoint / parentTotalAllocPoint) * lpPercent /1000;
}
if(newTokenPerSec != tokenPerSec) {
_massUpdatePools();
emit EmissionRateUpdated(msg.sender, tokenPerSec, newTokenPerSec);
tokenPerSec = newTokenPerSec;
}
}
functionupdateAllocPoint(uint256 _pid, uint256 _allocPoint)
publiconlyOwner{
require(_pid !=0, "Not authorized");
_massUpdatePools();
emit AllocPointsUpdated(
msg.sender,
poolInfo[_pid].allocPoint,
_allocPoint
);
totalAllocPoint =
totalAllocPoint -
poolInfo[_pid].allocPoint +
_allocPoint;
poolInfo[_pid].allocPoint = _allocPoint;
}
functionpoolTotalLp(uint256 pid) externalviewreturns (uint256) {
return poolInfo[pid].totalLp;
}
// Function to harvest many pools in a single transactionfunctionharvestMany(uint256[] calldata _pids) publicnonReentrant{
require(_pids.length<=30, "harvest many: too many pool ids");
for (uint256 index =0; index < _pids.length; ++index) {
require(_pids[index] !=0, "Not authorized");
_deposit(msg.sender, _pids[index], 0);
}
}
//small imprecisions in update timing might result in reward tokens getting stuck in the contract//we add an admin function to retrieve them if necessary. The contract does not hold user assets in any form.functionrecoverRewardToken(uint amount) externalonlyOwner{
rewardToken.safeTransfer(owner(), amount);
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @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);
/**
* @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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address to, 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 `from` to `to` 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(addressfrom, address to, uint256 amount) externalreturns (bool);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)pragmasolidity ^0.8.0;import"../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/abstractcontractOwnableisContext{
addressprivate _owner;
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/modifieronlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/function_checkOwner() internalviewvirtual{
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/functionrenounceOwnership() publicvirtualonlyOwner{
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
require(newOwner !=address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/function_transferOwnership(address newOwner) internalvirtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
Contract Source Code
File 13 of 13: ReentrancyGuard.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)pragmasolidity ^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() {
_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 making it call a
* `private` function that does the actual work.
*/modifiernonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function_nonReentrantBefore() private{
// On the first call to nonReentrant, _status will be _NOT_ENTEREDrequire(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function_nonReentrantAfter() private{
// By storing the original value once again, a refund is triggered (see// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/function_reentrancyGuardEntered() internalviewreturns (bool) {
return _status == _ENTERED;
}
}