contract_name
stringlengths 1
61
| file_path
stringlengths 5
50.4k
| contract_address
stringlengths 42
42
| language
stringclasses 1
value | class_name
stringlengths 1
61
| class_code
stringlengths 4
330k
| class_documentation
stringlengths 0
29.1k
| class_documentation_type
stringclasses 6
values | func_name
stringlengths 0
62
| func_code
stringlengths 1
303k
| func_documentation
stringlengths 2
14.9k
| func_documentation_type
stringclasses 4
values | compiler_version
stringlengths 15
42
| license_type
stringclasses 14
values | swarm_source
stringlengths 0
71
| meta
dict | __index_level_0__
int64 0
60.4k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | findEpochId | function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
| //find an epoch index based on timestamp | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
11777,
12368
]
} | 2,207 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | lockedBalances | function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
| // Information on a user's locked balances | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
12415,
13243
]
} | 2,208 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | epochCount | function epochCount() external view returns (uint256) {
return epochs.length;
}
| //number of epochs | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
13266,
13353
]
} | 2,209 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | checkpointEpoch | function checkpointEpoch() external {
_checkpointEpoch();
}
| /* ========== MUTATIVE FUNCTIONS ========== */ | Comment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
13405,
13472
]
} | 2,210 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | _checkpointEpoch | function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
| //insert a new epoch if needed. fill in any gaps | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
13525,
14357
]
} | 2,211 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | lock | function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
| // Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
14465,
14724
]
} | 2,212 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | _lock | function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
| //lock tokens | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
14742,
16756
]
} | 2,213 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | _processExpiredLocks | function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
| // Withdraw all currently locked tokens where the unlock time has passed | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
16833,
19820
]
} | 2,214 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | processExpiredLocks | function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
| // Withdraw/relock all currently locked tokens where the unlock time has passed | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
20405,
20623
]
} | 2,215 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | processExpiredLocks | function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
| // Withdraw/relock all currently locked tokens where the unlock time has passed | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
20707,
20856
]
} | 2,216 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | getReward | function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
| // Claim all pending rewards | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
21137,
21765
]
} | 2,217 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | _notifyReward | function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
| /* ========== RESTRICTED FUNCTIONS ========== */ | Comment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
21819,
22417
]
} | 2,218 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | recoverERC20 | function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
| // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
23084,
23467
]
} | 2,219 |
|
USRProxy | USRProxy.sol | 0x2cd4e8d82f62a91b2299b083ba08532a6a96a13a | Solidity | USRProxy | contract USRProxy is AdminUpgradeabilityProxy {
constructor(address _implementation)
public
AdminUpgradeabilityProxy(_implementation)
{}
// Allow anyone to view the implementation address
function USRImplementation() external view returns (address) {
return _implementation();
}
} | USRImplementation | function USRImplementation() external view returns (address) {
return _implementation();
}
| // Allow anyone to view the implementation address | LineComment | v0.5.12+commit.7709ece9 | None | bzzr://9150c0111dbe858762bce487b3de4feac777a258966d7f1d795b8a905917ff4c | {
"func_code_index": [
224,
333
]
} | 2,220 |
||
YFPIPresaleRoundTwo | @openzeppelin/contracts/utils/ReentrancyGuard.sol | 0xfaa1e3390f452d98a8fc4dd92aaad55a5e831dd9 | Solidity | Crowdsale | contract Crowdsale is Context, ReentrancyGuard, Owned {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(_msgSender());
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
// _updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
// _postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
// function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
// function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
function withdrawAllToken(uint256 tokenAmount) public nonReentrant{
require(msg.sender == owner);
_deliverTokens(owner, tokenAmount);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | function () external payable {
buyTokens(_msgSender());
}
| /**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | bzzr://008b35a2ff710804b9dfcc06dff11aaa52f28fd3f624dbef8829f38aeaf90c26 | {
"func_code_index": [
2137,
2213
]
} | 2,221 |
|
YFPIPresaleRoundTwo | @openzeppelin/contracts/utils/ReentrancyGuard.sol | 0xfaa1e3390f452d98a8fc4dd92aaad55a5e831dd9 | Solidity | Crowdsale | contract Crowdsale is Context, ReentrancyGuard, Owned {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(_msgSender());
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
// _updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
// _postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
// function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
// function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
function withdrawAllToken(uint256 tokenAmount) public nonReentrant{
require(msg.sender == owner);
_deliverTokens(owner, tokenAmount);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | token | function token() public view returns (IERC20) {
return _token;
}
| /**
* @return the token being sold.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | bzzr://008b35a2ff710804b9dfcc06dff11aaa52f28fd3f624dbef8829f38aeaf90c26 | {
"func_code_index": [
2272,
2355
]
} | 2,222 |
YFPIPresaleRoundTwo | @openzeppelin/contracts/utils/ReentrancyGuard.sol | 0xfaa1e3390f452d98a8fc4dd92aaad55a5e831dd9 | Solidity | Crowdsale | contract Crowdsale is Context, ReentrancyGuard, Owned {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(_msgSender());
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
// _updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
// _postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
// function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
// function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
function withdrawAllToken(uint256 tokenAmount) public nonReentrant{
require(msg.sender == owner);
_deliverTokens(owner, tokenAmount);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | wallet | function wallet() public view returns (address payable) {
return _wallet;
}
| /**
* @return the address where funds are collected.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | bzzr://008b35a2ff710804b9dfcc06dff11aaa52f28fd3f624dbef8829f38aeaf90c26 | {
"func_code_index": [
2431,
2525
]
} | 2,223 |
YFPIPresaleRoundTwo | @openzeppelin/contracts/utils/ReentrancyGuard.sol | 0xfaa1e3390f452d98a8fc4dd92aaad55a5e831dd9 | Solidity | Crowdsale | contract Crowdsale is Context, ReentrancyGuard, Owned {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(_msgSender());
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
// _updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
// _postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
// function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
// function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
function withdrawAllToken(uint256 tokenAmount) public nonReentrant{
require(msg.sender == owner);
_deliverTokens(owner, tokenAmount);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | rate | function rate() public view returns (uint256) {
return _rate;
}
| /**
* @return the number of token units a buyer gets per wei.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | bzzr://008b35a2ff710804b9dfcc06dff11aaa52f28fd3f624dbef8829f38aeaf90c26 | {
"func_code_index": [
2610,
2692
]
} | 2,224 |
YFPIPresaleRoundTwo | @openzeppelin/contracts/utils/ReentrancyGuard.sol | 0xfaa1e3390f452d98a8fc4dd92aaad55a5e831dd9 | Solidity | Crowdsale | contract Crowdsale is Context, ReentrancyGuard, Owned {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(_msgSender());
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
// _updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
// _postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
// function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
// function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
function withdrawAllToken(uint256 tokenAmount) public nonReentrant{
require(msg.sender == owner);
_deliverTokens(owner, tokenAmount);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | weiRaised | function weiRaised() public view returns (uint256) {
return _weiRaised;
}
| /**
* @return the amount of wei raised.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | bzzr://008b35a2ff710804b9dfcc06dff11aaa52f28fd3f624dbef8829f38aeaf90c26 | {
"func_code_index": [
2755,
2847
]
} | 2,225 |
YFPIPresaleRoundTwo | @openzeppelin/contracts/utils/ReentrancyGuard.sol | 0xfaa1e3390f452d98a8fc4dd92aaad55a5e831dd9 | Solidity | Crowdsale | contract Crowdsale is Context, ReentrancyGuard, Owned {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(_msgSender());
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
// _updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
// _postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
// function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
// function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
function withdrawAllToken(uint256 tokenAmount) public nonReentrant{
require(msg.sender == owner);
_deliverTokens(owner, tokenAmount);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | buyTokens | function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
// _updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
// _postValidatePurchase(beneficiary, weiAmount);
}
| /**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | bzzr://008b35a2ff710804b9dfcc06dff11aaa52f28fd3f624dbef8829f38aeaf90c26 | {
"func_code_index": [
3107,
3740
]
} | 2,226 |
YFPIPresaleRoundTwo | @openzeppelin/contracts/utils/ReentrancyGuard.sol | 0xfaa1e3390f452d98a8fc4dd92aaad55a5e831dd9 | Solidity | Crowdsale | contract Crowdsale is Context, ReentrancyGuard, Owned {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(_msgSender());
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
// _updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
// _postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
// function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
// function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
function withdrawAllToken(uint256 tokenAmount) public nonReentrant{
require(msg.sender == owner);
_deliverTokens(owner, tokenAmount);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | _preValidatePurchase | function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
}
| /**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | bzzr://008b35a2ff710804b9dfcc06dff11aaa52f28fd3f624dbef8829f38aeaf90c26 | {
"func_code_index": [
4288,
4673
]
} | 2,227 |
YFPIPresaleRoundTwo | @openzeppelin/contracts/utils/ReentrancyGuard.sol | 0xfaa1e3390f452d98a8fc4dd92aaad55a5e831dd9 | Solidity | Crowdsale | contract Crowdsale is Context, ReentrancyGuard, Owned {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(_msgSender());
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
// _updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
// _postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
// function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
// function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
function withdrawAllToken(uint256 tokenAmount) public nonReentrant{
require(msg.sender == owner);
_deliverTokens(owner, tokenAmount);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | _deliverTokens | function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
| /**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | bzzr://008b35a2ff710804b9dfcc06dff11aaa52f28fd3f624dbef8829f38aeaf90c26 | {
"func_code_index": [
5419,
5563
]
} | 2,228 |
YFPIPresaleRoundTwo | @openzeppelin/contracts/utils/ReentrancyGuard.sol | 0xfaa1e3390f452d98a8fc4dd92aaad55a5e831dd9 | Solidity | Crowdsale | contract Crowdsale is Context, ReentrancyGuard, Owned {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(_msgSender());
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
// _updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
// _postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
// function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
// function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
function withdrawAllToken(uint256 tokenAmount) public nonReentrant{
require(msg.sender == owner);
_deliverTokens(owner, tokenAmount);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | _processPurchase | function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
| /**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | bzzr://008b35a2ff710804b9dfcc06dff11aaa52f28fd3f624dbef8829f38aeaf90c26 | {
"func_code_index": [
5832,
5973
]
} | 2,229 |
YFPIPresaleRoundTwo | @openzeppelin/contracts/utils/ReentrancyGuard.sol | 0xfaa1e3390f452d98a8fc4dd92aaad55a5e831dd9 | Solidity | Crowdsale | contract Crowdsale is Context, ReentrancyGuard, Owned {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(_msgSender());
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
// _updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
// _postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
// function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
// function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
function withdrawAllToken(uint256 tokenAmount) public nonReentrant{
require(msg.sender == owner);
_deliverTokens(owner, tokenAmount);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | _getTokenAmount | function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
| /**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | bzzr://008b35a2ff710804b9dfcc06dff11aaa52f28fd3f624dbef8829f38aeaf90c26 | {
"func_code_index": [
6658,
6785
]
} | 2,230 |
YFPIPresaleRoundTwo | @openzeppelin/contracts/utils/ReentrancyGuard.sol | 0xfaa1e3390f452d98a8fc4dd92aaad55a5e831dd9 | Solidity | Crowdsale | contract Crowdsale is Context, ReentrancyGuard, Owned {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(_msgSender());
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
// _updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
// _postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
// function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
// function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// // solhint-disable-previous-line no-empty-blocks
// }
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
function withdrawAllToken(uint256 tokenAmount) public nonReentrant{
require(msg.sender == owner);
_deliverTokens(owner, tokenAmount);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | _forwardFunds | function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
| /**
* @dev Determines how ETH is stored/forwarded on purchases.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | bzzr://008b35a2ff710804b9dfcc06dff11aaa52f28fd3f624dbef8829f38aeaf90c26 | {
"func_code_index": [
6872,
6957
]
} | 2,231 |
UnidoBurner | UnidoBurner.sol | 0xe14f0298a42e1a266fec67c4b9dc4d75a02422e9 | Solidity | UnidoBurner | contract UnidoBurner is UnidoDistribution {
using SafeMath for uint256;
// Storing the instance of UDO Token in udo variable.
UnidoDistribution udo = UnidoDistribution(0xea3983Fc6D0fbbC41fb6F6091f68F3e08894dC06);
// Events triggered during the execution of respective code blocks
event Stage1(bool applicable);
event Stage2(bool applicable);
event TokensBurnt(uint256 numberOfBurntTokens);
mapping (address => bool) private moderator;
// Declaring the limit at which Stage 2 is triggered.
uint256 constant limit = 92000000 * 10**decimals;
constructor() {
// Owner of the contract is by default a moderator.
// Owner of CFBF must be the owner of UDO ERC-20 Contract.
moderator[msg.sender] = true;
}
modifier onlyModerator {
require(moderator[msg.sender] == true, 'Only the moderators allowed by the owner of the contract can do that');
_;
}
// Can be called only by the owner of the contract. Give access to certain people to call distribute() function.
function addModerator(address _mod) public onlyOwner {
moderator[_mod] = true;
}
// Can be called only by the moderators.
// Distribute any number of tokens from the contract address.
function distribute(uint256 tokens) public onlyModerator {
require(tokens > 0, "Cannot distribute 0 Tokens!");
require(tokens <= 1000000 * 10**decimals, "Cannot distribute more than 1 million UDO Tokens at once!");
// Fetching the total supply.
uint256 supply = udo.totalSupply();
// Target distribution addresses
address EDF = 0x2F9BF79fbd31345B33A76E3D630C173823af27cB;
address reserve = 0x5c80F9982DcCc3F2C8b4CbDFdf60E684798e4284;
uint256 actualAllocationStage_1 = 0;
uint256 actualAllocationStage_2 = 0;
// Maximum Tokens that can follow Stage 1 are
// (supply - limit) / 0.6
uint256 maxAllocationStage_1 = supply.sub(limit).div(6).mul(10);
if(tokens > maxAllocationStage_1) {
actualAllocationStage_2 = tokens.sub(maxAllocationStage_1);
} else {
actualAllocationStage_2 = 0;
}
actualAllocationStage_1 = tokens.sub(actualAllocationStage_2);
// actualAllocationStage_1 = actualAllocationStage_1.div(10);
uint256 tokensToBurn = 0;
uint256 tokensToEDFandReserve = 0;
// Stage 1 : Burnt at 60/20/20 down to limit
if(actualAllocationStage_1 > 0) {
// Follow Stage 1:
// Burn: 60%,
// Reserve: 20%,
// EDF: 20%.
tokensToEDFandReserve = actualAllocationStage_1.mul(2).div(10);
tokensToBurn = actualAllocationStage_1.sub(tokensToEDFandReserve.mul(2));
udo.burn(tokensToBurn);
TokensBurnt(tokensToBurn);
udo.transfer(reserve, tokensToEDFandReserve);
udo.transfer(EDF, tokensToEDFandReserve);
Stage1(true);
}
// Stage 2
if(actualAllocationStage_2 > 0) {
// Follow Stage 2:
// Reserve: 50%,
// EDF: 50%.
actualAllocationStage_2 = actualAllocationStage_2.div(2);
udo.transfer(reserve, actualAllocationStage_2);
udo.transfer(EDF, actualAllocationStage_2);
Stage2(true);
}
}
} | addModerator | function addModerator(address _mod) public onlyOwner {
moderator[_mod] = true;
}
| // Can be called only by the owner of the contract. Give access to certain people to call distribute() function. | LineComment | v0.7.0+commit.9e61f92b | MIT | ipfs://f346129fa95d0c46e011ecb72ebfcd13e87c5d651f7110069c27b31977d9095e | {
"func_code_index": [
1118,
1217
]
} | 2,232 |
||
UnidoBurner | UnidoBurner.sol | 0xe14f0298a42e1a266fec67c4b9dc4d75a02422e9 | Solidity | UnidoBurner | contract UnidoBurner is UnidoDistribution {
using SafeMath for uint256;
// Storing the instance of UDO Token in udo variable.
UnidoDistribution udo = UnidoDistribution(0xea3983Fc6D0fbbC41fb6F6091f68F3e08894dC06);
// Events triggered during the execution of respective code blocks
event Stage1(bool applicable);
event Stage2(bool applicable);
event TokensBurnt(uint256 numberOfBurntTokens);
mapping (address => bool) private moderator;
// Declaring the limit at which Stage 2 is triggered.
uint256 constant limit = 92000000 * 10**decimals;
constructor() {
// Owner of the contract is by default a moderator.
// Owner of CFBF must be the owner of UDO ERC-20 Contract.
moderator[msg.sender] = true;
}
modifier onlyModerator {
require(moderator[msg.sender] == true, 'Only the moderators allowed by the owner of the contract can do that');
_;
}
// Can be called only by the owner of the contract. Give access to certain people to call distribute() function.
function addModerator(address _mod) public onlyOwner {
moderator[_mod] = true;
}
// Can be called only by the moderators.
// Distribute any number of tokens from the contract address.
function distribute(uint256 tokens) public onlyModerator {
require(tokens > 0, "Cannot distribute 0 Tokens!");
require(tokens <= 1000000 * 10**decimals, "Cannot distribute more than 1 million UDO Tokens at once!");
// Fetching the total supply.
uint256 supply = udo.totalSupply();
// Target distribution addresses
address EDF = 0x2F9BF79fbd31345B33A76E3D630C173823af27cB;
address reserve = 0x5c80F9982DcCc3F2C8b4CbDFdf60E684798e4284;
uint256 actualAllocationStage_1 = 0;
uint256 actualAllocationStage_2 = 0;
// Maximum Tokens that can follow Stage 1 are
// (supply - limit) / 0.6
uint256 maxAllocationStage_1 = supply.sub(limit).div(6).mul(10);
if(tokens > maxAllocationStage_1) {
actualAllocationStage_2 = tokens.sub(maxAllocationStage_1);
} else {
actualAllocationStage_2 = 0;
}
actualAllocationStage_1 = tokens.sub(actualAllocationStage_2);
// actualAllocationStage_1 = actualAllocationStage_1.div(10);
uint256 tokensToBurn = 0;
uint256 tokensToEDFandReserve = 0;
// Stage 1 : Burnt at 60/20/20 down to limit
if(actualAllocationStage_1 > 0) {
// Follow Stage 1:
// Burn: 60%,
// Reserve: 20%,
// EDF: 20%.
tokensToEDFandReserve = actualAllocationStage_1.mul(2).div(10);
tokensToBurn = actualAllocationStage_1.sub(tokensToEDFandReserve.mul(2));
udo.burn(tokensToBurn);
TokensBurnt(tokensToBurn);
udo.transfer(reserve, tokensToEDFandReserve);
udo.transfer(EDF, tokensToEDFandReserve);
Stage1(true);
}
// Stage 2
if(actualAllocationStage_2 > 0) {
// Follow Stage 2:
// Reserve: 50%,
// EDF: 50%.
actualAllocationStage_2 = actualAllocationStage_2.div(2);
udo.transfer(reserve, actualAllocationStage_2);
udo.transfer(EDF, actualAllocationStage_2);
Stage2(true);
}
}
} | distribute | function distribute(uint256 tokens) public onlyModerator {
require(tokens > 0, "Cannot distribute 0 Tokens!");
require(tokens <= 1000000 * 10**decimals, "Cannot distribute more than 1 million UDO Tokens at once!");
// Fetching the total supply.
uint256 supply = udo.totalSupply();
// Target distribution addresses
address EDF = 0x2F9BF79fbd31345B33A76E3D630C173823af27cB;
address reserve = 0x5c80F9982DcCc3F2C8b4CbDFdf60E684798e4284;
uint256 actualAllocationStage_1 = 0;
uint256 actualAllocationStage_2 = 0;
// Maximum Tokens that can follow Stage 1 are
// (supply - limit) / 0.6
uint256 maxAllocationStage_1 = supply.sub(limit).div(6).mul(10);
if(tokens > maxAllocationStage_1) {
actualAllocationStage_2 = tokens.sub(maxAllocationStage_1);
} else {
actualAllocationStage_2 = 0;
}
actualAllocationStage_1 = tokens.sub(actualAllocationStage_2);
// actualAllocationStage_1 = actualAllocationStage_1.div(10);
uint256 tokensToBurn = 0;
uint256 tokensToEDFandReserve = 0;
// Stage 1 : Burnt at 60/20/20 down to limit
if(actualAllocationStage_1 > 0) {
// Follow Stage 1:
// Burn: 60%,
// Reserve: 20%,
// EDF: 20%.
tokensToEDFandReserve = actualAllocationStage_1.mul(2).div(10);
tokensToBurn = actualAllocationStage_1.sub(tokensToEDFandReserve.mul(2));
udo.burn(tokensToBurn);
TokensBurnt(tokensToBurn);
udo.transfer(reserve, tokensToEDFandReserve);
udo.transfer(EDF, tokensToEDFandReserve);
Stage1(true);
}
// Stage 2
if(actualAllocationStage_2 > 0) {
// Follow Stage 2:
// Reserve: 50%,
// EDF: 50%.
actualAllocationStage_2 = actualAllocationStage_2.div(2);
udo.transfer(reserve, actualAllocationStage_2);
udo.transfer(EDF, actualAllocationStage_2);
Stage2(true);
}
}
| // Can be called only by the moderators.
// Distribute any number of tokens from the contract address. | LineComment | v0.7.0+commit.9e61f92b | MIT | ipfs://f346129fa95d0c46e011ecb72ebfcd13e87c5d651f7110069c27b31977d9095e | {
"func_code_index": [
1333,
3611
]
} | 2,233 |
||
PuppyToken | BasicToken.sol | 0x7d952579e9936b1b31e6f5c177313fe0d1629635 | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
} | /**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/ | NatSpecMultiLine | totalSupply | function totalSupply() public view returns (uint256) {
return totalSupply_;
}
| /**
* @dev total number of tokens in existence
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://53966b522fee9bd9487e71f4de5b60d7c60f73981ab202213db2e5d782b98406 | {
"func_code_index": [
189,
274
]
} | 2,234 |
|
PuppyToken | BasicToken.sol | 0x7d952579e9936b1b31e6f5c177313fe0d1629635 | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
} | /**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/ | NatSpecMultiLine | transfer | function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
| /**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://53966b522fee9bd9487e71f4de5b60d7c60f73981ab202213db2e5d782b98406 | {
"func_code_index": [
426,
807
]
} | 2,235 |
|
PuppyToken | BasicToken.sol | 0x7d952579e9936b1b31e6f5c177313fe0d1629635 | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
} | /**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
| /**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://53966b522fee9bd9487e71f4de5b60d7c60f73981ab202213db2e5d782b98406 | {
"func_code_index": [
1007,
1116
]
} | 2,236 |
|
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | Ownable | abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @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.
*/ | NatSpecMultiLine | owner | function owner() public view returns (address) {
return _owner;
}
| /**
* @dev Returns the address of the current owner.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
497,
581
]
} | 2,237 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | Ownable | abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @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.
*/ | NatSpecMultiLine | renounceOwnership | function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
| /**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
1139,
1292
]
} | 2,238 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | Ownable | abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @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.
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| /**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
1442,
1691
]
} | 2,239 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | Pausable | abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
} | /**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/ | NatSpecMultiLine | paused | function paused() public view returns (bool) {
return _paused;
}
| /**
* @dev Returns true if the contract is paused, and false otherwise.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
531,
614
]
} | 2,240 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | Pausable | abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
} | /**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/ | NatSpecMultiLine | _pause | function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
| /**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
1321,
1444
]
} | 2,241 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | Pausable | abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
} | /**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/ | NatSpecMultiLine | _unpause | function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
| /**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
1580,
1705
]
} | 2,242 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @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.
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
| /**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
259,
445
]
} | 2,243 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @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.
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
| /**
* @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.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
723,
864
]
} | 2,244 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @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.
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
| /**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
1162,
1359
]
} | 2,245 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @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.
*/ | NatSpecMultiLine | mul | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
| /**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
1613,
2089
]
} | 2,246 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @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.
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
| /**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
2560,
2697
]
} | 2,247 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @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.
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| /**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message 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.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
3188,
3471
]
} | 2,248 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @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.
*/ | NatSpecMultiLine | mod | function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
| /**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts 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.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
3931,
4066
]
} | 2,249 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @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.
*/ | NatSpecMultiLine | mod | function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
| /**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message 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.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
4546,
4717
]
} | 2,250 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | totalSupply | function totalSupply() external view returns (uint256);
| /**
* @dev Returns the amount of tokens in existence.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
94,
154
]
} | 2,251 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address account) external view returns (uint256);
| /**
* @dev Returns the amount of tokens owned by `account`.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
237,
310
]
} | 2,252 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | transfer | function transfer(address recipient, uint256 amount) external returns (bool);
| /**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
534,
616
]
} | 2,253 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | allowance | function allowance(address owner, address spender) external view returns (uint256);
| /**
* @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.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
895,
983
]
} | 2,254 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | approve | function approve(address spender, uint256 amount) external returns (bool);
| /**
* @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.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
1647,
1726
]
} | 2,255 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
| /**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
2039,
2141
]
} | 2,256 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | name | function name() public view returns (string memory) {
return _name;
}
| /**
* @dev Returns the name of the token.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
867,
955
]
} | 2,257 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | symbol | function symbol() public view returns (string memory) {
return _symbol;
}
| /**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
1069,
1161
]
} | 2,258 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | decimals | function decimals() public view returns (uint8) {
return _decimals;
}
| /**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
1794,
1882
]
} | 2,259 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | totalSupply | function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
| /**
* @dev See {IERC20-totalSupply}.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
1942,
2047
]
} | 2,260 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
| /**
* @dev See {IERC20-balanceOf}.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
2105,
2229
]
} | 2,261 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | transfer | function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
| /**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
2437,
2617
]
} | 2,262 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | allowance | function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
| /**
* @dev See {IERC20-allowance}.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
2675,
2831
]
} | 2,263 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | approve | function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
| /**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
2973,
3147
]
} | 2,264 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
| /**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
3624,
3950
]
} | 2,265 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | increaseAllowance | function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
| /**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
4354,
4577
]
} | 2,266 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | decreaseAllowance | function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
| /**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
5075,
5349
]
} | 2,267 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _transfer | function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| /**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
5834,
6378
]
} | 2,268 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _mint | function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
| /** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
6655,
7038
]
} | 2,269 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _burn | function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
| /**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
7366,
7789
]
} | 2,270 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _approve | function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| /**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
8222,
8573
]
} | 2,271 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _setupDecimals | function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
| /**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
8900,
8995
]
} | 2,272 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _beforeTokenTransfer | function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
| /**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
9593,
9690
]
} | 2,273 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | Address | library Address {
/**
* @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
* ====
*/
function isContract(address account) internal view returns (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-assembly
assembly { 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].
*/
function sendValue(address payable 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._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
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._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
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, bytes memory 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._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
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._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | isContract | function isContract(address account) internal view returns (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-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
| /**
* @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
* ====
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
606,
1033
]
} | 2,274 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | Address | library Address {
/**
* @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
* ====
*/
function isContract(address account) internal view returns (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-assembly
assembly { 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].
*/
function sendValue(address payable 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._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
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._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
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, bytes memory 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._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
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._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | sendValue | function sendValue(address payable 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 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].
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
1963,
2365
]
} | 2,275 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | Address | library Address {
/**
* @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
* ====
*/
function isContract(address account) internal view returns (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-assembly
assembly { 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].
*/
function sendValue(address payable 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._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
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._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
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, bytes memory 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._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
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._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCall | function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
| /**
* @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._
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
3121,
3299
]
} | 2,276 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | Address | library Address {
/**
* @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
* ====
*/
function isContract(address account) internal view returns (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-assembly
assembly { 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].
*/
function sendValue(address payable 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._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
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._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
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, bytes memory 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._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
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._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCall | function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
3524,
3724
]
} | 2,277 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | Address | library Address {
/**
* @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
* ====
*/
function isContract(address account) internal view returns (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-assembly
assembly { 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].
*/
function sendValue(address payable 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._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
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._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
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, bytes memory 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._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
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._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCallWithValue | function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
| /**
* @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._
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
4094,
4325
]
} | 2,278 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | Address | library Address {
/**
* @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
* ====
*/
function isContract(address account) internal view returns (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-assembly
assembly { 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].
*/
function sendValue(address payable 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._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
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._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
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, bytes memory 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._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
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._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCallWithValue | function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
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, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
| /**
* @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._
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
4576,
5111
]
} | 2,279 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | Address | library Address {
/**
* @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
* ====
*/
function isContract(address account) internal view returns (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-assembly
assembly { 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].
*/
function sendValue(address payable 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._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
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._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
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, bytes memory 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._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
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._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionStaticCall | function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
5291,
5495
]
} | 2,280 |
EVNToken | EVNToken.sol | 0x8888888861ba162cb37b98792e9427fcd77f1c24 | Solidity | Address | library Address {
/**
* @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
* ====
*/
function isContract(address account) internal view returns (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-assembly
assembly { 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].
*/
function sendValue(address payable 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._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
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._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
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, bytes memory 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._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
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._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionStaticCall | function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://eea4c366a5d2b1a62c20f1b7d8b51ee6ca4765817e13539cbf7ff4256a988d4d | {
"func_code_index": [
5682,
6109
]
} | 2,281 |
lockRSG | lockRSG.sol | 0x0b5b7aabd6a22a5bd1297ba74c0435ca34555674 | Solidity | lockRSG | contract lockRSG is owned{
using SafeMath for uint256;
/*
* deposit vars
*/
struct Items {
address tokenAddress;
address withdrawalAddress;
uint256 tokenAmount;
uint256 unlockTime;
bool withdrawn;
}
uint256 public depositId;
uint256[] public allDepositIds;
mapping (address => uint256[]) public depositsByWithdrawalAddress;
mapping (uint256 => Items) public lockedToken;
mapping (address => mapping(address => uint256)) public walletTokenBalance;
event LogWithdrawal(address SentToAddress, uint256 AmountTransferred);
/**
* Constrctor function
*/
constructor() public {
}
/**
*lock tokens
*/
function lockTokens(address _tokenAddress, uint256 _amount, uint256 _unlockTime) public returns (uint256 _id) {
require(_amount > 0, 'token amount is Zero');
require(_unlockTime < 10000000000, 'Enter an unix timestamp in seconds, not miliseconds');
require(Token(_tokenAddress).approve(this, _amount), 'Approve tokens failed');
require(Token(_tokenAddress).transferFrom(msg.sender, this, _amount), 'Transfer of tokens failed');
//update balance in address
_amount = _amount * 95 / 100;
walletTokenBalance[_tokenAddress][msg.sender] = walletTokenBalance[_tokenAddress][msg.sender].add(_amount);
address _withdrawalAddress = msg.sender;
_id = ++depositId;
lockedToken[_id].tokenAddress = _tokenAddress;
lockedToken[_id].withdrawalAddress = _withdrawalAddress;
lockedToken[_id].tokenAmount = _amount;
lockedToken[_id].unlockTime = _unlockTime;
lockedToken[_id].withdrawn = false;
allDepositIds.push(_id);
depositsByWithdrawalAddress[_withdrawalAddress].push(_id);
}
/**
*withdraw tokens
*/
function withdrawTokens(uint256 _id) public {
require(block.timestamp >= lockedToken[_id].unlockTime, 'Tokens are locked');
require(msg.sender == lockedToken[_id].withdrawalAddress, 'Can withdraw by withdrawal Address only');
require(!lockedToken[_id].withdrawn, 'Tokens already withdrawn');
require(Token(lockedToken[_id].tokenAddress).transfer(msg.sender, lockedToken[_id].tokenAmount), 'Transfer of tokens failed');
lockedToken[_id].withdrawn = true;
//update balance in address
walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender].sub(lockedToken[_id].tokenAmount);
//remove this id from this address
uint256 i; uint256 j;
for(j=0; j<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length; j++){
if(depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id){
for (i = j; i<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length-1; i++){
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i] = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i+1];
}
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length--;
break;
}
}
emit LogWithdrawal(msg.sender, lockedToken[_id].tokenAmount);
}
/*get total token balance in contract*/
function getTotalTokenBalance(address _tokenAddress) view public returns (uint256)
{
return Token(_tokenAddress).balanceOf(this);
}
/*get total token balance by address*/
function getTokenBalanceByAddress(address _tokenAddress, address _walletAddress) view public returns (uint256)
{
return walletTokenBalance[_tokenAddress][_walletAddress];
}
/*get allDepositIds*/
function getAllDepositIds() view public returns (uint256[])
{
return allDepositIds;
}
/*get getDepositDetails*/
function getDepositDetails(uint256 _id) view public returns (address, address, uint256, uint256, bool)
{
return(lockedToken[_id].tokenAddress,lockedToken[_id].withdrawalAddress,lockedToken[_id].tokenAmount,
lockedToken[_id].unlockTime,lockedToken[_id].withdrawn);
}
/*get DepositsByWithdrawalAddress*/
function getDepositsByWithdrawalAddress(address _withdrawalAddress) view public returns (uint256[])
{
return depositsByWithdrawalAddress[_withdrawalAddress];
}
} | lockTokens | function lockTokens(address _tokenAddress, uint256 _amount, uint256 _unlockTime) public returns (uint256 _id) {
require(_amount > 0, 'token amount is Zero');
require(_unlockTime < 10000000000, 'Enter an unix timestamp in seconds, not miliseconds');
require(Token(_tokenAddress).approve(this, _amount), 'Approve tokens failed');
require(Token(_tokenAddress).transferFrom(msg.sender, this, _amount), 'Transfer of tokens failed');
//update balance in address
_amount = _amount * 95 / 100;
walletTokenBalance[_tokenAddress][msg.sender] = walletTokenBalance[_tokenAddress][msg.sender].add(_amount);
address _withdrawalAddress = msg.sender;
_id = ++depositId;
lockedToken[_id].tokenAddress = _tokenAddress;
lockedToken[_id].withdrawalAddress = _withdrawalAddress;
lockedToken[_id].tokenAmount = _amount;
lockedToken[_id].unlockTime = _unlockTime;
lockedToken[_id].withdrawn = false;
allDepositIds.push(_id);
depositsByWithdrawalAddress[_withdrawalAddress].push(_id);
}
| /**
*lock tokens
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | None | bzzr://9a00a94249611acee7460d358e9b805271d065b0e739d502b3faf10b51ef2983 | {
"func_code_index": [
781,
1927
]
} | 2,282 |
||
lockRSG | lockRSG.sol | 0x0b5b7aabd6a22a5bd1297ba74c0435ca34555674 | Solidity | lockRSG | contract lockRSG is owned{
using SafeMath for uint256;
/*
* deposit vars
*/
struct Items {
address tokenAddress;
address withdrawalAddress;
uint256 tokenAmount;
uint256 unlockTime;
bool withdrawn;
}
uint256 public depositId;
uint256[] public allDepositIds;
mapping (address => uint256[]) public depositsByWithdrawalAddress;
mapping (uint256 => Items) public lockedToken;
mapping (address => mapping(address => uint256)) public walletTokenBalance;
event LogWithdrawal(address SentToAddress, uint256 AmountTransferred);
/**
* Constrctor function
*/
constructor() public {
}
/**
*lock tokens
*/
function lockTokens(address _tokenAddress, uint256 _amount, uint256 _unlockTime) public returns (uint256 _id) {
require(_amount > 0, 'token amount is Zero');
require(_unlockTime < 10000000000, 'Enter an unix timestamp in seconds, not miliseconds');
require(Token(_tokenAddress).approve(this, _amount), 'Approve tokens failed');
require(Token(_tokenAddress).transferFrom(msg.sender, this, _amount), 'Transfer of tokens failed');
//update balance in address
_amount = _amount * 95 / 100;
walletTokenBalance[_tokenAddress][msg.sender] = walletTokenBalance[_tokenAddress][msg.sender].add(_amount);
address _withdrawalAddress = msg.sender;
_id = ++depositId;
lockedToken[_id].tokenAddress = _tokenAddress;
lockedToken[_id].withdrawalAddress = _withdrawalAddress;
lockedToken[_id].tokenAmount = _amount;
lockedToken[_id].unlockTime = _unlockTime;
lockedToken[_id].withdrawn = false;
allDepositIds.push(_id);
depositsByWithdrawalAddress[_withdrawalAddress].push(_id);
}
/**
*withdraw tokens
*/
function withdrawTokens(uint256 _id) public {
require(block.timestamp >= lockedToken[_id].unlockTime, 'Tokens are locked');
require(msg.sender == lockedToken[_id].withdrawalAddress, 'Can withdraw by withdrawal Address only');
require(!lockedToken[_id].withdrawn, 'Tokens already withdrawn');
require(Token(lockedToken[_id].tokenAddress).transfer(msg.sender, lockedToken[_id].tokenAmount), 'Transfer of tokens failed');
lockedToken[_id].withdrawn = true;
//update balance in address
walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender].sub(lockedToken[_id].tokenAmount);
//remove this id from this address
uint256 i; uint256 j;
for(j=0; j<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length; j++){
if(depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id){
for (i = j; i<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length-1; i++){
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i] = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i+1];
}
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length--;
break;
}
}
emit LogWithdrawal(msg.sender, lockedToken[_id].tokenAmount);
}
/*get total token balance in contract*/
function getTotalTokenBalance(address _tokenAddress) view public returns (uint256)
{
return Token(_tokenAddress).balanceOf(this);
}
/*get total token balance by address*/
function getTokenBalanceByAddress(address _tokenAddress, address _walletAddress) view public returns (uint256)
{
return walletTokenBalance[_tokenAddress][_walletAddress];
}
/*get allDepositIds*/
function getAllDepositIds() view public returns (uint256[])
{
return allDepositIds;
}
/*get getDepositDetails*/
function getDepositDetails(uint256 _id) view public returns (address, address, uint256, uint256, bool)
{
return(lockedToken[_id].tokenAddress,lockedToken[_id].withdrawalAddress,lockedToken[_id].tokenAmount,
lockedToken[_id].unlockTime,lockedToken[_id].withdrawn);
}
/*get DepositsByWithdrawalAddress*/
function getDepositsByWithdrawalAddress(address _withdrawalAddress) view public returns (uint256[])
{
return depositsByWithdrawalAddress[_withdrawalAddress];
}
} | withdrawTokens | function withdrawTokens(uint256 _id) public {
require(block.timestamp >= lockedToken[_id].unlockTime, 'Tokens are locked');
require(msg.sender == lockedToken[_id].withdrawalAddress, 'Can withdraw by withdrawal Address only');
require(!lockedToken[_id].withdrawn, 'Tokens already withdrawn');
require(Token(lockedToken[_id].tokenAddress).transfer(msg.sender, lockedToken[_id].tokenAmount), 'Transfer of tokens failed');
lockedToken[_id].withdrawn = true;
//update balance in address
walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender].sub(lockedToken[_id].tokenAmount);
//remove this id from this address
uint256 i; uint256 j;
for(j=0; j<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length; j++){
if(depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id){
for (i = j; i<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length-1; i++){
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i] = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i+1];
}
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length--;
break;
}
}
emit LogWithdrawal(msg.sender, lockedToken[_id].tokenAmount);
}
| /**
*withdraw tokens
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | None | bzzr://9a00a94249611acee7460d358e9b805271d065b0e739d502b3faf10b51ef2983 | {
"func_code_index": [
1974,
3488
]
} | 2,283 |
||
lockRSG | lockRSG.sol | 0x0b5b7aabd6a22a5bd1297ba74c0435ca34555674 | Solidity | lockRSG | contract lockRSG is owned{
using SafeMath for uint256;
/*
* deposit vars
*/
struct Items {
address tokenAddress;
address withdrawalAddress;
uint256 tokenAmount;
uint256 unlockTime;
bool withdrawn;
}
uint256 public depositId;
uint256[] public allDepositIds;
mapping (address => uint256[]) public depositsByWithdrawalAddress;
mapping (uint256 => Items) public lockedToken;
mapping (address => mapping(address => uint256)) public walletTokenBalance;
event LogWithdrawal(address SentToAddress, uint256 AmountTransferred);
/**
* Constrctor function
*/
constructor() public {
}
/**
*lock tokens
*/
function lockTokens(address _tokenAddress, uint256 _amount, uint256 _unlockTime) public returns (uint256 _id) {
require(_amount > 0, 'token amount is Zero');
require(_unlockTime < 10000000000, 'Enter an unix timestamp in seconds, not miliseconds');
require(Token(_tokenAddress).approve(this, _amount), 'Approve tokens failed');
require(Token(_tokenAddress).transferFrom(msg.sender, this, _amount), 'Transfer of tokens failed');
//update balance in address
_amount = _amount * 95 / 100;
walletTokenBalance[_tokenAddress][msg.sender] = walletTokenBalance[_tokenAddress][msg.sender].add(_amount);
address _withdrawalAddress = msg.sender;
_id = ++depositId;
lockedToken[_id].tokenAddress = _tokenAddress;
lockedToken[_id].withdrawalAddress = _withdrawalAddress;
lockedToken[_id].tokenAmount = _amount;
lockedToken[_id].unlockTime = _unlockTime;
lockedToken[_id].withdrawn = false;
allDepositIds.push(_id);
depositsByWithdrawalAddress[_withdrawalAddress].push(_id);
}
/**
*withdraw tokens
*/
function withdrawTokens(uint256 _id) public {
require(block.timestamp >= lockedToken[_id].unlockTime, 'Tokens are locked');
require(msg.sender == lockedToken[_id].withdrawalAddress, 'Can withdraw by withdrawal Address only');
require(!lockedToken[_id].withdrawn, 'Tokens already withdrawn');
require(Token(lockedToken[_id].tokenAddress).transfer(msg.sender, lockedToken[_id].tokenAmount), 'Transfer of tokens failed');
lockedToken[_id].withdrawn = true;
//update balance in address
walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender].sub(lockedToken[_id].tokenAmount);
//remove this id from this address
uint256 i; uint256 j;
for(j=0; j<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length; j++){
if(depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id){
for (i = j; i<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length-1; i++){
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i] = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i+1];
}
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length--;
break;
}
}
emit LogWithdrawal(msg.sender, lockedToken[_id].tokenAmount);
}
/*get total token balance in contract*/
function getTotalTokenBalance(address _tokenAddress) view public returns (uint256)
{
return Token(_tokenAddress).balanceOf(this);
}
/*get total token balance by address*/
function getTokenBalanceByAddress(address _tokenAddress, address _walletAddress) view public returns (uint256)
{
return walletTokenBalance[_tokenAddress][_walletAddress];
}
/*get allDepositIds*/
function getAllDepositIds() view public returns (uint256[])
{
return allDepositIds;
}
/*get getDepositDetails*/
function getDepositDetails(uint256 _id) view public returns (address, address, uint256, uint256, bool)
{
return(lockedToken[_id].tokenAddress,lockedToken[_id].withdrawalAddress,lockedToken[_id].tokenAmount,
lockedToken[_id].unlockTime,lockedToken[_id].withdrawn);
}
/*get DepositsByWithdrawalAddress*/
function getDepositsByWithdrawalAddress(address _withdrawalAddress) view public returns (uint256[])
{
return depositsByWithdrawalAddress[_withdrawalAddress];
}
} | getTotalTokenBalance | function getTotalTokenBalance(address _tokenAddress) view public returns (uint256)
{
return Token(_tokenAddress).balanceOf(this);
}
| /*get total token balance in contract*/ | Comment | v0.4.25+commit.59dbf8f1 | None | bzzr://9a00a94249611acee7460d358e9b805271d065b0e739d502b3faf10b51ef2983 | {
"func_code_index": [
3537,
3691
]
} | 2,284 |
||
lockRSG | lockRSG.sol | 0x0b5b7aabd6a22a5bd1297ba74c0435ca34555674 | Solidity | lockRSG | contract lockRSG is owned{
using SafeMath for uint256;
/*
* deposit vars
*/
struct Items {
address tokenAddress;
address withdrawalAddress;
uint256 tokenAmount;
uint256 unlockTime;
bool withdrawn;
}
uint256 public depositId;
uint256[] public allDepositIds;
mapping (address => uint256[]) public depositsByWithdrawalAddress;
mapping (uint256 => Items) public lockedToken;
mapping (address => mapping(address => uint256)) public walletTokenBalance;
event LogWithdrawal(address SentToAddress, uint256 AmountTransferred);
/**
* Constrctor function
*/
constructor() public {
}
/**
*lock tokens
*/
function lockTokens(address _tokenAddress, uint256 _amount, uint256 _unlockTime) public returns (uint256 _id) {
require(_amount > 0, 'token amount is Zero');
require(_unlockTime < 10000000000, 'Enter an unix timestamp in seconds, not miliseconds');
require(Token(_tokenAddress).approve(this, _amount), 'Approve tokens failed');
require(Token(_tokenAddress).transferFrom(msg.sender, this, _amount), 'Transfer of tokens failed');
//update balance in address
_amount = _amount * 95 / 100;
walletTokenBalance[_tokenAddress][msg.sender] = walletTokenBalance[_tokenAddress][msg.sender].add(_amount);
address _withdrawalAddress = msg.sender;
_id = ++depositId;
lockedToken[_id].tokenAddress = _tokenAddress;
lockedToken[_id].withdrawalAddress = _withdrawalAddress;
lockedToken[_id].tokenAmount = _amount;
lockedToken[_id].unlockTime = _unlockTime;
lockedToken[_id].withdrawn = false;
allDepositIds.push(_id);
depositsByWithdrawalAddress[_withdrawalAddress].push(_id);
}
/**
*withdraw tokens
*/
function withdrawTokens(uint256 _id) public {
require(block.timestamp >= lockedToken[_id].unlockTime, 'Tokens are locked');
require(msg.sender == lockedToken[_id].withdrawalAddress, 'Can withdraw by withdrawal Address only');
require(!lockedToken[_id].withdrawn, 'Tokens already withdrawn');
require(Token(lockedToken[_id].tokenAddress).transfer(msg.sender, lockedToken[_id].tokenAmount), 'Transfer of tokens failed');
lockedToken[_id].withdrawn = true;
//update balance in address
walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender].sub(lockedToken[_id].tokenAmount);
//remove this id from this address
uint256 i; uint256 j;
for(j=0; j<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length; j++){
if(depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id){
for (i = j; i<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length-1; i++){
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i] = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i+1];
}
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length--;
break;
}
}
emit LogWithdrawal(msg.sender, lockedToken[_id].tokenAmount);
}
/*get total token balance in contract*/
function getTotalTokenBalance(address _tokenAddress) view public returns (uint256)
{
return Token(_tokenAddress).balanceOf(this);
}
/*get total token balance by address*/
function getTokenBalanceByAddress(address _tokenAddress, address _walletAddress) view public returns (uint256)
{
return walletTokenBalance[_tokenAddress][_walletAddress];
}
/*get allDepositIds*/
function getAllDepositIds() view public returns (uint256[])
{
return allDepositIds;
}
/*get getDepositDetails*/
function getDepositDetails(uint256 _id) view public returns (address, address, uint256, uint256, bool)
{
return(lockedToken[_id].tokenAddress,lockedToken[_id].withdrawalAddress,lockedToken[_id].tokenAmount,
lockedToken[_id].unlockTime,lockedToken[_id].withdrawn);
}
/*get DepositsByWithdrawalAddress*/
function getDepositsByWithdrawalAddress(address _withdrawalAddress) view public returns (uint256[])
{
return depositsByWithdrawalAddress[_withdrawalAddress];
}
} | getTokenBalanceByAddress | function getTokenBalanceByAddress(address _tokenAddress, address _walletAddress) view public returns (uint256)
{
return walletTokenBalance[_tokenAddress][_walletAddress];
}
| /*get total token balance by address*/ | Comment | v0.4.25+commit.59dbf8f1 | None | bzzr://9a00a94249611acee7460d358e9b805271d065b0e739d502b3faf10b51ef2983 | {
"func_code_index": [
3742,
3937
]
} | 2,285 |
||
lockRSG | lockRSG.sol | 0x0b5b7aabd6a22a5bd1297ba74c0435ca34555674 | Solidity | lockRSG | contract lockRSG is owned{
using SafeMath for uint256;
/*
* deposit vars
*/
struct Items {
address tokenAddress;
address withdrawalAddress;
uint256 tokenAmount;
uint256 unlockTime;
bool withdrawn;
}
uint256 public depositId;
uint256[] public allDepositIds;
mapping (address => uint256[]) public depositsByWithdrawalAddress;
mapping (uint256 => Items) public lockedToken;
mapping (address => mapping(address => uint256)) public walletTokenBalance;
event LogWithdrawal(address SentToAddress, uint256 AmountTransferred);
/**
* Constrctor function
*/
constructor() public {
}
/**
*lock tokens
*/
function lockTokens(address _tokenAddress, uint256 _amount, uint256 _unlockTime) public returns (uint256 _id) {
require(_amount > 0, 'token amount is Zero');
require(_unlockTime < 10000000000, 'Enter an unix timestamp in seconds, not miliseconds');
require(Token(_tokenAddress).approve(this, _amount), 'Approve tokens failed');
require(Token(_tokenAddress).transferFrom(msg.sender, this, _amount), 'Transfer of tokens failed');
//update balance in address
_amount = _amount * 95 / 100;
walletTokenBalance[_tokenAddress][msg.sender] = walletTokenBalance[_tokenAddress][msg.sender].add(_amount);
address _withdrawalAddress = msg.sender;
_id = ++depositId;
lockedToken[_id].tokenAddress = _tokenAddress;
lockedToken[_id].withdrawalAddress = _withdrawalAddress;
lockedToken[_id].tokenAmount = _amount;
lockedToken[_id].unlockTime = _unlockTime;
lockedToken[_id].withdrawn = false;
allDepositIds.push(_id);
depositsByWithdrawalAddress[_withdrawalAddress].push(_id);
}
/**
*withdraw tokens
*/
function withdrawTokens(uint256 _id) public {
require(block.timestamp >= lockedToken[_id].unlockTime, 'Tokens are locked');
require(msg.sender == lockedToken[_id].withdrawalAddress, 'Can withdraw by withdrawal Address only');
require(!lockedToken[_id].withdrawn, 'Tokens already withdrawn');
require(Token(lockedToken[_id].tokenAddress).transfer(msg.sender, lockedToken[_id].tokenAmount), 'Transfer of tokens failed');
lockedToken[_id].withdrawn = true;
//update balance in address
walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender].sub(lockedToken[_id].tokenAmount);
//remove this id from this address
uint256 i; uint256 j;
for(j=0; j<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length; j++){
if(depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id){
for (i = j; i<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length-1; i++){
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i] = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i+1];
}
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length--;
break;
}
}
emit LogWithdrawal(msg.sender, lockedToken[_id].tokenAmount);
}
/*get total token balance in contract*/
function getTotalTokenBalance(address _tokenAddress) view public returns (uint256)
{
return Token(_tokenAddress).balanceOf(this);
}
/*get total token balance by address*/
function getTokenBalanceByAddress(address _tokenAddress, address _walletAddress) view public returns (uint256)
{
return walletTokenBalance[_tokenAddress][_walletAddress];
}
/*get allDepositIds*/
function getAllDepositIds() view public returns (uint256[])
{
return allDepositIds;
}
/*get getDepositDetails*/
function getDepositDetails(uint256 _id) view public returns (address, address, uint256, uint256, bool)
{
return(lockedToken[_id].tokenAddress,lockedToken[_id].withdrawalAddress,lockedToken[_id].tokenAmount,
lockedToken[_id].unlockTime,lockedToken[_id].withdrawn);
}
/*get DepositsByWithdrawalAddress*/
function getDepositsByWithdrawalAddress(address _withdrawalAddress) view public returns (uint256[])
{
return depositsByWithdrawalAddress[_withdrawalAddress];
}
} | getAllDepositIds | function getAllDepositIds() view public returns (uint256[])
{
return allDepositIds;
}
| /*get allDepositIds*/ | Comment | v0.4.25+commit.59dbf8f1 | None | bzzr://9a00a94249611acee7460d358e9b805271d065b0e739d502b3faf10b51ef2983 | {
"func_code_index": [
3971,
4080
]
} | 2,286 |
||
lockRSG | lockRSG.sol | 0x0b5b7aabd6a22a5bd1297ba74c0435ca34555674 | Solidity | lockRSG | contract lockRSG is owned{
using SafeMath for uint256;
/*
* deposit vars
*/
struct Items {
address tokenAddress;
address withdrawalAddress;
uint256 tokenAmount;
uint256 unlockTime;
bool withdrawn;
}
uint256 public depositId;
uint256[] public allDepositIds;
mapping (address => uint256[]) public depositsByWithdrawalAddress;
mapping (uint256 => Items) public lockedToken;
mapping (address => mapping(address => uint256)) public walletTokenBalance;
event LogWithdrawal(address SentToAddress, uint256 AmountTransferred);
/**
* Constrctor function
*/
constructor() public {
}
/**
*lock tokens
*/
function lockTokens(address _tokenAddress, uint256 _amount, uint256 _unlockTime) public returns (uint256 _id) {
require(_amount > 0, 'token amount is Zero');
require(_unlockTime < 10000000000, 'Enter an unix timestamp in seconds, not miliseconds');
require(Token(_tokenAddress).approve(this, _amount), 'Approve tokens failed');
require(Token(_tokenAddress).transferFrom(msg.sender, this, _amount), 'Transfer of tokens failed');
//update balance in address
_amount = _amount * 95 / 100;
walletTokenBalance[_tokenAddress][msg.sender] = walletTokenBalance[_tokenAddress][msg.sender].add(_amount);
address _withdrawalAddress = msg.sender;
_id = ++depositId;
lockedToken[_id].tokenAddress = _tokenAddress;
lockedToken[_id].withdrawalAddress = _withdrawalAddress;
lockedToken[_id].tokenAmount = _amount;
lockedToken[_id].unlockTime = _unlockTime;
lockedToken[_id].withdrawn = false;
allDepositIds.push(_id);
depositsByWithdrawalAddress[_withdrawalAddress].push(_id);
}
/**
*withdraw tokens
*/
function withdrawTokens(uint256 _id) public {
require(block.timestamp >= lockedToken[_id].unlockTime, 'Tokens are locked');
require(msg.sender == lockedToken[_id].withdrawalAddress, 'Can withdraw by withdrawal Address only');
require(!lockedToken[_id].withdrawn, 'Tokens already withdrawn');
require(Token(lockedToken[_id].tokenAddress).transfer(msg.sender, lockedToken[_id].tokenAmount), 'Transfer of tokens failed');
lockedToken[_id].withdrawn = true;
//update balance in address
walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender].sub(lockedToken[_id].tokenAmount);
//remove this id from this address
uint256 i; uint256 j;
for(j=0; j<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length; j++){
if(depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id){
for (i = j; i<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length-1; i++){
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i] = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i+1];
}
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length--;
break;
}
}
emit LogWithdrawal(msg.sender, lockedToken[_id].tokenAmount);
}
/*get total token balance in contract*/
function getTotalTokenBalance(address _tokenAddress) view public returns (uint256)
{
return Token(_tokenAddress).balanceOf(this);
}
/*get total token balance by address*/
function getTokenBalanceByAddress(address _tokenAddress, address _walletAddress) view public returns (uint256)
{
return walletTokenBalance[_tokenAddress][_walletAddress];
}
/*get allDepositIds*/
function getAllDepositIds() view public returns (uint256[])
{
return allDepositIds;
}
/*get getDepositDetails*/
function getDepositDetails(uint256 _id) view public returns (address, address, uint256, uint256, bool)
{
return(lockedToken[_id].tokenAddress,lockedToken[_id].withdrawalAddress,lockedToken[_id].tokenAmount,
lockedToken[_id].unlockTime,lockedToken[_id].withdrawn);
}
/*get DepositsByWithdrawalAddress*/
function getDepositsByWithdrawalAddress(address _withdrawalAddress) view public returns (uint256[])
{
return depositsByWithdrawalAddress[_withdrawalAddress];
}
} | getDepositDetails | function getDepositDetails(uint256 _id) view public returns (address, address, uint256, uint256, bool)
{
return(lockedToken[_id].tokenAddress,lockedToken[_id].withdrawalAddress,lockedToken[_id].tokenAmount,
lockedToken[_id].unlockTime,lockedToken[_id].withdrawn);
}
| /*get getDepositDetails*/ | Comment | v0.4.25+commit.59dbf8f1 | None | bzzr://9a00a94249611acee7460d358e9b805271d065b0e739d502b3faf10b51ef2983 | {
"func_code_index": [
4118,
4416
]
} | 2,287 |
||
lockRSG | lockRSG.sol | 0x0b5b7aabd6a22a5bd1297ba74c0435ca34555674 | Solidity | lockRSG | contract lockRSG is owned{
using SafeMath for uint256;
/*
* deposit vars
*/
struct Items {
address tokenAddress;
address withdrawalAddress;
uint256 tokenAmount;
uint256 unlockTime;
bool withdrawn;
}
uint256 public depositId;
uint256[] public allDepositIds;
mapping (address => uint256[]) public depositsByWithdrawalAddress;
mapping (uint256 => Items) public lockedToken;
mapping (address => mapping(address => uint256)) public walletTokenBalance;
event LogWithdrawal(address SentToAddress, uint256 AmountTransferred);
/**
* Constrctor function
*/
constructor() public {
}
/**
*lock tokens
*/
function lockTokens(address _tokenAddress, uint256 _amount, uint256 _unlockTime) public returns (uint256 _id) {
require(_amount > 0, 'token amount is Zero');
require(_unlockTime < 10000000000, 'Enter an unix timestamp in seconds, not miliseconds');
require(Token(_tokenAddress).approve(this, _amount), 'Approve tokens failed');
require(Token(_tokenAddress).transferFrom(msg.sender, this, _amount), 'Transfer of tokens failed');
//update balance in address
_amount = _amount * 95 / 100;
walletTokenBalance[_tokenAddress][msg.sender] = walletTokenBalance[_tokenAddress][msg.sender].add(_amount);
address _withdrawalAddress = msg.sender;
_id = ++depositId;
lockedToken[_id].tokenAddress = _tokenAddress;
lockedToken[_id].withdrawalAddress = _withdrawalAddress;
lockedToken[_id].tokenAmount = _amount;
lockedToken[_id].unlockTime = _unlockTime;
lockedToken[_id].withdrawn = false;
allDepositIds.push(_id);
depositsByWithdrawalAddress[_withdrawalAddress].push(_id);
}
/**
*withdraw tokens
*/
function withdrawTokens(uint256 _id) public {
require(block.timestamp >= lockedToken[_id].unlockTime, 'Tokens are locked');
require(msg.sender == lockedToken[_id].withdrawalAddress, 'Can withdraw by withdrawal Address only');
require(!lockedToken[_id].withdrawn, 'Tokens already withdrawn');
require(Token(lockedToken[_id].tokenAddress).transfer(msg.sender, lockedToken[_id].tokenAmount), 'Transfer of tokens failed');
lockedToken[_id].withdrawn = true;
//update balance in address
walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender].sub(lockedToken[_id].tokenAmount);
//remove this id from this address
uint256 i; uint256 j;
for(j=0; j<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length; j++){
if(depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id){
for (i = j; i<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length-1; i++){
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i] = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i+1];
}
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length--;
break;
}
}
emit LogWithdrawal(msg.sender, lockedToken[_id].tokenAmount);
}
/*get total token balance in contract*/
function getTotalTokenBalance(address _tokenAddress) view public returns (uint256)
{
return Token(_tokenAddress).balanceOf(this);
}
/*get total token balance by address*/
function getTokenBalanceByAddress(address _tokenAddress, address _walletAddress) view public returns (uint256)
{
return walletTokenBalance[_tokenAddress][_walletAddress];
}
/*get allDepositIds*/
function getAllDepositIds() view public returns (uint256[])
{
return allDepositIds;
}
/*get getDepositDetails*/
function getDepositDetails(uint256 _id) view public returns (address, address, uint256, uint256, bool)
{
return(lockedToken[_id].tokenAddress,lockedToken[_id].withdrawalAddress,lockedToken[_id].tokenAmount,
lockedToken[_id].unlockTime,lockedToken[_id].withdrawn);
}
/*get DepositsByWithdrawalAddress*/
function getDepositsByWithdrawalAddress(address _withdrawalAddress) view public returns (uint256[])
{
return depositsByWithdrawalAddress[_withdrawalAddress];
}
} | getDepositsByWithdrawalAddress | function getDepositsByWithdrawalAddress(address _withdrawalAddress) view public returns (uint256[])
{
return depositsByWithdrawalAddress[_withdrawalAddress];
}
| /*get DepositsByWithdrawalAddress*/ | Comment | v0.4.25+commit.59dbf8f1 | None | bzzr://9a00a94249611acee7460d358e9b805271d065b0e739d502b3faf10b51ef2983 | {
"func_code_index": [
4464,
4647
]
} | 2,288 |
||
PlatToken | PlatToken.sol | 0x609b942a62e72aa6147b053bbf0728e9f256b542 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | totalSupply | function totalSupply() external view returns (uint256);
| /**
* @dev Returns the amount of tokens in existence.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://5406d119dbdc8318fe2a54c9d65668410fc14d1f818c8fd4e277fdf42d924bb5 | {
"func_code_index": [
94,
154
]
} | 2,289 |
||
PlatToken | PlatToken.sol | 0x609b942a62e72aa6147b053bbf0728e9f256b542 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | balanceOf | function balanceOf(address account) external view returns (uint256);
| /**
* @dev Returns the amount of tokens owned by `account`.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://5406d119dbdc8318fe2a54c9d65668410fc14d1f818c8fd4e277fdf42d924bb5 | {
"func_code_index": [
237,
310
]
} | 2,290 |
||
PlatToken | PlatToken.sol | 0x609b942a62e72aa6147b053bbf0728e9f256b542 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
} | name | function name() public view returns (string memory) {
return _name;
}
| /**
* @dev Returns the name of the token.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://5406d119dbdc8318fe2a54c9d65668410fc14d1f818c8fd4e277fdf42d924bb5 | {
"func_code_index": [
545,
633
]
} | 2,291 |
||
PlatToken | PlatToken.sol | 0x609b942a62e72aa6147b053bbf0728e9f256b542 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
} | totalSupply | function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
| /**
* @dev See {IERC20-totalSupply}.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://5406d119dbdc8318fe2a54c9d65668410fc14d1f818c8fd4e277fdf42d924bb5 | {
"func_code_index": [
879,
984
]
} | 2,292 |
||
PlatToken | PlatToken.sol | 0x609b942a62e72aa6147b053bbf0728e9f256b542 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
} | balanceOf | function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
| /**
* @dev See {IERC20-balanceOf}.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://5406d119dbdc8318fe2a54c9d65668410fc14d1f818c8fd4e277fdf42d924bb5 | {
"func_code_index": [
1042,
1166
]
} | 2,293 |
||
PuppyToken | SafeMath.sol | 0x7d952579e9936b1b31e6f5c177313fe0d1629635 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | mul | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
| /**
* @dev Multiplies two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://53966b522fee9bd9487e71f4de5b60d7c60f73981ab202213db2e5d782b98406 | {
"func_code_index": [
84,
259
]
} | 2,294 |
|
PuppyToken | SafeMath.sol | 0x7d952579e9936b1b31e6f5c177313fe0d1629635 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| /**
* @dev Integer division of two numbers, truncating the quotient.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://53966b522fee9bd9487e71f4de5b60d7c60f73981ab202213db2e5d782b98406 | {
"func_code_index": [
339,
606
]
} | 2,295 |
|
PuppyToken | SafeMath.sol | 0x7d952579e9936b1b31e6f5c177313fe0d1629635 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
| /**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://53966b522fee9bd9487e71f4de5b60d7c60f73981ab202213db2e5d782b98406 | {
"func_code_index": [
717,
829
]
} | 2,296 |
|
PuppyToken | SafeMath.sol | 0x7d952579e9936b1b31e6f5c177313fe0d1629635 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
| /**
* @dev Adds two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://53966b522fee9bd9487e71f4de5b60d7c60f73981ab202213db2e5d782b98406 | {
"func_code_index": [
889,
1020
]
} | 2,297 |
|
Starpunks | /home/projects/projects/nftsclub/contract/contracts/Starpunks.sol | 0xa9f3065fea7d1ddc95df3dec97e5651c1745ac0d | Solidity | Starpunks | contract Starpunks is ERC721Enumerable, Ownable {
uint public constant MAX_SUPPLY = 6038;
string _baseTokenURI = "https://starpunk.nftsclub.io/";
bool public isActive = true;
uint256 unitPrice = 60000000000000000; // 0.06 ether
uint256 maxPerUser = 20;
constructor() ERC721("Starpunks", "STP") {
address _to = 0x713ba7a2B5271aeb8600b5ee4142Bb9758e3921F;
for(uint i = 0; i < 40; i++){
_safeMint(_to, totalSupply());
}
}
function mint(address _to, uint _count) public payable {
require(isActive, "!active");
require(_count <= maxPerUser, "> maxPerUser");
require(totalSupply() < MAX_SUPPLY, "Ended");
require(totalSupply() + _count <= MAX_SUPPLY, ">limit");
require(msg.value >= price(_count), "!value");
for(uint i = 0; i < _count; i++){
_safeMint(_to, totalSupply());
}
}
function price(uint _count) public view returns (uint256) {
return _count * unitPrice;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
function walletOfOwner(address _owner) external view returns(uint256[] memory) {
uint tokenCount = balanceOf(_owner);
uint256[] memory tokensIds = new uint256[](tokenCount);
for(uint i = 0; i < tokenCount; i++){
tokensIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensIds;
}
function setActive(bool _active) public onlyOwner {
isActive = _active;
}
// allows the owner to withdraw BNB and other tokens
function ownerWithdraw(uint256 amount, address _to, address _tokenAddr) public onlyOwner{
require(_to != address(0));
if(_tokenAddr == address(0)){
payable(_to).transfer(amount);
}else{
StandardToken(_tokenAddr).transfer(_to, amount);
}
}
} | ownerWithdraw | function ownerWithdraw(uint256 amount, address _to, address _tokenAddr) public onlyOwner{
require(_to != address(0));
if(_tokenAddr == address(0)){
payable(_to).transfer(amount);
}else{
StandardToken(_tokenAddr).transfer(_to, amount);
}
}
| // allows the owner to withdraw BNB and other tokens | LineComment | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
1605,
1877
]
} | 2,298 |
||||
ChrisBell | ChrisBell.sol | 0xf071a4a5086a71af034ae895288da437e2722469 | Solidity | EIP20Interface | contract EIP20Interface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | balanceOf | function balanceOf(address _owner) public view returns (uint256 balance);
| /// @param _owner The address from which the balance will be retrieved
/// @return The balance | NatSpecSingleLine | v0.4.23+commit.124ca40d | bzzr://16640e72790020e794e7ca23c1f63fdc0ec2ff68079b1598ec14333b7f5873b7 | {
"func_code_index": [
638,
716
]
} | 2,299 |
|||
ChrisBell | ChrisBell.sol | 0xf071a4a5086a71af034ae895288da437e2722469 | Solidity | EIP20Interface | contract EIP20Interface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transfer | function transfer(address _to, uint256 _value) public returns (bool success);
| /// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.23+commit.124ca40d | bzzr://16640e72790020e794e7ca23c1f63fdc0ec2ff68079b1598ec14333b7f5873b7 | {
"func_code_index": [
953,
1035
]
} | 2,300 |
|||
ChrisBell | ChrisBell.sol | 0xf071a4a5086a71af034ae895288da437e2722469 | Solidity | EIP20Interface | contract EIP20Interface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
| /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.23+commit.124ca40d | bzzr://16640e72790020e794e7ca23c1f63fdc0ec2ff68079b1598ec14333b7f5873b7 | {
"func_code_index": [
1358,
1459
]
} | 2,301 |
|||
ChrisBell | ChrisBell.sol | 0xf071a4a5086a71af034ae895288da437e2722469 | Solidity | EIP20Interface | contract EIP20Interface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | approve | function approve(address _spender, uint256 _value) public returns (bool success);
| /// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not | NatSpecSingleLine | v0.4.23+commit.124ca40d | bzzr://16640e72790020e794e7ca23c1f63fdc0ec2ff68079b1598ec14333b7f5873b7 | {
"func_code_index": [
1749,
1835
]
} | 2,302 |
|||
ChrisBell | ChrisBell.sol | 0xf071a4a5086a71af034ae895288da437e2722469 | Solidity | EIP20Interface | contract EIP20Interface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | allowance | function allowance(address _owner, address _spender) public view returns (uint256 remaining);
| /// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent | NatSpecSingleLine | v0.4.23+commit.124ca40d | bzzr://16640e72790020e794e7ca23c1f63fdc0ec2ff68079b1598ec14333b7f5873b7 | {
"func_code_index": [
2043,
2141
]
} | 2,303 |
|||
ChrisBell | ChrisBell.sol | 0xf071a4a5086a71af034ae895288da437e2722469 | Solidity | ChrisBell | contract ChrisBell is EIP20Interface {
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show.
string public symbol; //An identifier: eg SBX
function ChrisBell(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) public {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | ChrisBell | function ChrisBell(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) public {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
| //An identifier: eg SBX | LineComment | v0.4.23+commit.124ca40d | bzzr://16640e72790020e794e7ca23c1f63fdc0ec2ff68079b1598ec14333b7f5873b7 | {
"func_code_index": [
726,
1384
]
} | 2,304 |
|||
FUNGI | openzeppelin-solidity\contracts\access\Ownable.sol | 0xe918925a67b49897d0780b22b738610068a18bb4 | Solidity | Ownable | abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @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.
*/ | NatSpecMultiLine | owner | function owner() public view virtual returns (address) {
return _owner;
}
| /**
* @dev Returns the address of the current owner.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://ba56817785df0acf93679ae6f6ce9a37dd503964e25888163ecfcef472d79be2 | {
"func_code_index": [
521,
613
]
} | 2,305 |
FUNGI | openzeppelin-solidity\contracts\access\Ownable.sol | 0xe918925a67b49897d0780b22b738610068a18bb4 | Solidity | Ownable | abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @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.
*/ | NatSpecMultiLine | renounceOwnership | function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
| /**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://ba56817785df0acf93679ae6f6ce9a37dd503964e25888163ecfcef472d79be2 | {
"func_code_index": [
1172,
1325
]
} | 2,306 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.